In this section, you will learn to validate a xml file against a DTD (Document Type Definition) using the DOM APIs. A DTD defines the document structure with a list of legal elements and attributes.
Description of program:
Validating a XML file against a DTD needs a xml file and its DTD document. First of all construct a well-formed xml file along with a DTD file . This DTD file defines all elements to keep in the xml file. After creating these, we parse the xml file using the parse() method and generates a Document object tree. The setErrorHandler() method invokes an object of DoucmentBuilder. Enable the setValidating() method of the factory to "true". If we pass 'true' the parser will validate xml documents otherwise not. To validate xml file , pass the DTD file as setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "Employee.dtd") in the transformer object.
Here is the xml file: Employeexy.xml
| <?xml version = "1.0" ?> <!DOCTYPE Employee SYSTEM "Employee.dtd"> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail> </Employee> |
Here is the DTD File: Employee.dtd
| <!ELEMENT Employee (Emp_Id, Emp_Name, Emp_E-mail)> <!ELEMENT Emp_Id (#PCDATA)> <!ELEMENT Emp_Name (#PCDATA)> <!ELEMENT Emp_E-mail (#PCDATA)> |
Here is the Java file: DOMValidateDTD.java
import java.io.*;
|
Output of this program:
| C:\vinod\xml>javac DOMValidateDTD.java C:\vinod\xml>java DOMValidateDTD <?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE Employee SYSTEM "Employee.dtd"> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> Vinod1@yahoo.com </Emp_E-mail> </Employee> |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: XML Validate DTD View All Comments
Post your Comment