What's the best way to validate an XML file against an XSD file?

前端 未结 13 1479
滥情空心
滥情空心 2020-11-22 07:37

I\'m generating some xml files that needs to conform to an xsd file that was given to me. What\'s the best way to verify they conform?

13条回答
  •  无人共我
    2020-11-22 08:38

    Here's how to do it using Xerces2. A tutorial for this, here (req. signup).

    Original attribution: blatantly copied from here:

    import org.apache.xerces.parsers.DOMParser;
    import java.io.File;
    import org.w3c.dom.Document;
    
    public class SchemaTest {
      public static void main (String args[]) {
          File docFile = new File("memory.xml");
          try {
            DOMParser parser = new DOMParser();
            parser.setFeature("http://xml.org/sax/features/validation", true);
            parser.setProperty(
                 "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", 
                 "memory.xsd");
            ErrorChecker errors = new ErrorChecker();
            parser.setErrorHandler(errors);
            parser.parse("memory.xml");
         } catch (Exception e) {
            System.out.print("Problem parsing the file.");
         }
      }
    }
    

提交回复
热议问题