How to validate xml with dtd using java?
Asked Answered
K

2

16

I have following xml file:

<?xml version = "1.0" ?>
<Employee>
    <Emp_Id>E-001</Emp_Id>
    <Emp_Name>Vinod</Emp_Name>
    <Emp_E-mail>[email protected]</Emp_E-mail>
</Employee>

I have following dtd file:

<!ELEMENT Employee (Emp_Id, Emp_Name, Emp_E-mail)>
<!ELEMENT Emp_Id (#PCDATA)>
<!ELEMENT Emp_Name (#PCDATA)>
<!ELEMENT Emp_E-mail (#PCDATA)>

I want to validate this xml file with above dtd using java.

Please, help thanks..:-)

Kratzer answered 2/1, 2012 at 10:14 Comment(0)
D
20

There are three things you should do:

  • Associate the source XML document with its DTD using a doctype declaration after the XML declaration:

    <!DOCTYPE Employee SYSTEM "employee.dtd">
    

    Note: The DOCTYPE root must match the root element in the source XML.

  • setValidating to true on the DocumentBuilderFactory

  • Provide an org.xml.sax.ErrorHandler instance to the DocumentBuilder using setErrorHandler

Here's a complete example:

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setValidating(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
    @Override
    public void error(SAXParseException exception) throws SAXException {
        // do something more useful in each of these handlers
        exception.printStackTrace();
    }
    @Override
    public void fatalError(SAXParseException exception) throws SAXException {
        exception.printStackTrace();
    }

    @Override
    public void warning(SAXParseException exception) throws SAXException {
        exception.printStackTrace();
    }
});
Document doc = builder.parse("employee.xml");

Source document:

<?xml version="1.0"?>
<!DOCTYPE Employee SYSTEM "employee.dtd">
<Employee>
    <Emp_Id> E-001</Emp_Id>
    <Emp_Name> Vinod </Emp_Name>
    <Emp_E-mail> [email protected] </Emp_E-mail>
</Employee>
Doomsday answered 3/1, 2012 at 19:52 Comment(3)
Thanks lwburk!! but I dont allow to change in original source xml file.Kratzer
@SachinJ - read the file into memory, insert the DOCTYPE line, have the builder parse the XML string instead of a disk file.Jukebox
Sorry for the question but... where should I set the DTD filepath of the file set as "SYSTEM"?Tiffanitiffanie
M
1

You just need to read the files and report the exceptions, if any. Here is a SAX parser example you can rely upon.

In order to validate your XML and DTD you just need to setValidating:

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true); // since the default value is false

Also declare the DTD usage in your XML file:

<?xml version="1.0"?>
<!DOCTYPE Employee SYSTEM "employee.dtd">
<Employee>
Mazza answered 2/1, 2012 at 10:21 Comment(1)
Document root element "Employee", must match DOCTYPE root "employee".Doomsday

© 2022 - 2024 — McMap. All rights reserved.