Hi friend,
Step to validate a xml file against a DTD (Document Type Definition) using the DOM APIs.
Here is the xml file "User.xml"
<?xml version = "1.0" ?>
<!DOCTYPE User SYSTEM "User.dtd">
<User>
<User_Id>1 </User_Id>
<User_Name> Vineet </User_Name>
<User_mail>
[email protected]</User_mail>
</User>
Here is the DTD file "User.xml"
<!ELEMENT User (User_Id, User_Name, User_mail)>
<!ELEMENT User_Id (#PCDATA)>
<!ELEMENT User_Name (#PCDATA)>
<!ELEMENT User_mail (#PCDATA)>
import java.io.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.validation.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
"ValidateUserXml.java" code to validate the xml.
public class ValidateUserXml {
public static void main(String args[]) {
try{
DocumentBuilderFactory docBuildFactory = DocumentBuilderFactory.newInstance();
docBuildFactory.setValidating(true);
DocumentBuilder docBuild = docBuildFactory.newDocumentBuilder();
docBuild.setErrorHandler(new org.xml.sax.ErrorHandler() {
//Ignore the fatal errors
public void fatalError(SAXParseException exception)throws SAXException { }
//Validation errors
public void error(SAXParseException e)throws SAXParseException {
System.out.println("Error at " +e.getLineNumber() + " line.");
System.out.println(e.getMessage());
System.exit(0);
}
//Show warnings
public void warning(SAXParseException err)throws SAXParseException{
System.out.println(err.getMessage());
System.exit(0);
}
});
Document doc = docBuild.parse(new FileInputStream("User.xml"));
DOMSource domSrc = new DOMSource(doc);
StreamResult streamResult = new StreamResult(System.out);
TransformerFactory transFact = TransformerFactory.newInstance();
Transformer transformer = transFact.newTransformer();
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "User.dtd");
transformer.transform(domSrc, streamResult);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Thanks