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

前端 未结 13 1327
滥情空心
滥情空心 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条回答
  •  旧时难觅i
    2020-11-22 08:21

    Since this is a popular question, I will point out that java can also validate against "referred to" xsd's, for instance if the .xml file itself specifies XSD's in the header, using xsi:schemaLocation or xsi:noNamespaceSchemaLocation (or xsi for particular namespaces) ex:

    
      ...
    

    or schemaLocation (always a list of namespace to xsd mappings)

    
      ...
    

    The other answers work here as well, because the .xsd files "map" to the namespaces declared in the .xml file, because they declare a namespace, and if matches up with the namespace in the .xml file, you're good. But sometimes it's convenient to be able to have a custom resolver...

    From the javadocs: "If you create a schema without specifying a URL, file, or source, then the Java language creates one that looks in the document being validated to find the schema it should use. For example:"

    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = factory.newSchema();
    

    and this works for multiple namespaces, etc. The problem with this approach is that the xmlsns:xsi is probably a network location, so it'll by default go out and hit the network with each and every validation, not always optimal.

    Here's an example that validates an XML file against any XSD's it references (even if it has to pull them from the network):

      public static void verifyValidatesInternalXsd(String filename) throws Exception {
        InputStream xmlStream = new new FileInputStream(filename);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        factory.setNamespaceAware(true);
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                     "http://www.w3.org/2001/XMLSchema");
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setErrorHandler(new RaiseOnErrorHandler());
        builder.parse(new InputSource(xmlStream));
        xmlStream.close();
      }
    
      public static class RaiseOnErrorHandler implements ErrorHandler {
        public void warning(SAXParseException e) throws SAXException {
          throw new RuntimeException(e);
        }
        public void error(SAXParseException e) throws SAXException {
          throw new RuntimeException(e);
        }
        public void fatalError(SAXParseException e) throws SAXException {
          throw new RuntimeException(e);
        }
      }
    

    You can avoid pulling referenced XSD's from the network, even though the xml files reference url's, by specifying the xsd manually (see some other answers here) or by using an "XML catalog" style resolver. Spring apparently also can intercept the URL requests to serve local files for validations. Or you can set your own via setResourceResolver, ex:

    Source xmlFile = new StreamSource(xmlFileLocation);
    SchemaFactory schemaFactory = SchemaFactory
                                    .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema();
    Validator validator = schema.newValidator();
    validator.setResourceResolver(new LSResourceResolver() {
      @Override
      public LSInput resolveResource(String type, String namespaceURI,
                                     String publicId, String systemId, String baseURI) {
        InputSource is = new InputSource(
                               getClass().getResourceAsStream(
                              "some_local_file_in_the_jar.xsd"));
                              // or lookup by URI, etc...
        return new Input(is); // for class Input see 
                              // https://stackoverflow.com/a/2342859/32453
      }
    });
    validator.validate(xmlFile);
    

    See also here for another tutorial.

    I believe the default is to use DOM parsing, you can do something similar with SAX parser that is validating as well saxReader.setEntityResolver(your_resolver_here);

提交回复
热议问题