How to validate xml with dtd using java?

后端 未结 2 794
北海茫月
北海茫月 2020-12-31 06:35

I have following xml file:



 E-001
 Vinod  
&l         


        
相关标签:
2条回答
  • 2020-12-31 06:59

    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> Vinod1@yahoo.com </Emp_E-mail>
    </Employee>
    
    0 讨论(0)
  • 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>
    
    0 讨论(0)
提交回复
热议问题