【问题标题】:How to validate an XML file against an XSD file?根据 XSD 文件验证 XML 文件的最佳方法是什么?
【发布时间】:2010-09-06 03:44:01
【问题描述】:

我正在生成一些需要符合给我的 xsd 文件的 xml 文件。验证它们是否符合要求的最佳方法是什么?

【问题讨论】:

    标签: java xml validation xsd


    【解决方案1】:

    由于这是一个流行的问题,我将指出 java 还可以验证“引用”xsd,例如,如果 .xml 文件本身在标头中指定 XSD,则使用 xsi:schemaLocation 或 xsi:noNamespaceSchemaLocation(或xsi 用于特定命名空间)ex:

    <document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="http://www.example.com/document.xsd">
      ...
    

    或 schemaLocation(总是命名空间到 xsd 映射的列表)

    <document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.example.com/my_namespace http://www.example.com/document.xsd">
      ...
    

    其他答案在这里也有效,因为 .xsd 文件“映射”到 .xml 文件中声明的命名空间,因为它们声明了一个命名空间,并且如果与 .xml 文件中的命名空间匹配,你再好。但有时能够有一个自定义的resolver 会很方便...

    来自 javadocs:“如果您创建架构时没有指定 URL、文件或源,那么 Java 语言会创建一个查看正在验证的文档以找到它应该使用的架构的架构。例如:”

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

    这适用于多个命名空间等。 这种方法的问题在于,xmlsns:xsi 可能是一个网络位置,因此默认情况下,它会在每次验证时出去并访问网络,并不总是最优的。

    下面是一个例子,它根据它引用的任何 XSD 验证 XML 文件(即使它必须从网络中提取它们):

      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);
        }
      }
    

    您可以通过手动指定 xsd(请参阅此处的其他答案)或使用“XML 目录”style resolver 来避免从网络中提取引用的 XSD,即使 xml 文件引用了 url。 Spring 显然还 can intercept URL 请求为本地文件提供验证。或者您也可以通过setResourceResolver 自行设置,例如:

    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);
    

    另请参阅here 以获得另一个教程。

    我相信默认是使用 DOM 解析,你可以用 SAX 解析器做类似的事情来验证 as well saxReader.setEntityResolver(your_resolver_here);

    【讨论】:

    • 对我不起作用,除非它在 ​​schemaFactory 上设置,否则不会调用方法 resolveResource(),知道吗?
    • 不知道,对我有用。确保您通过setResourceResolver 设置它,但除此之外,可能会打开新问题...
    • 恢复一个旧帖子,我认为它应该是 xsi:schemaLocation 而不是 xsi:SchemaLocation - 大小写很重要。见w3.org/TR/xmlschema-1/#d0e3067
    【解决方案2】:

    使用 Java 7,您可以按照package description 中提供的文档进行操作。

    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    
    // load a WXS schema, represented by a Schema instance
    Source schemaFile = new StreamSource(new File("mySchema.xsd"));
    Schema schema = factory.newSchema(schemaFile);
    
    // create a Validator instance, which can be used to validate an instance document
    Validator validator = schema.newValidator();
    
    // validate the DOM tree
    try {
        validator.validate(new StreamSource(new File("instance.xml"));
    } catch (SAXException e) {
        // instance document is invalid!
    }
    

    【讨论】:

    • "Using Java 7.." 这实际上包含在Java 5中。
    • 这个和the accepted answer基本一样。这个解决方案在我看来有点低效,因为它不必要地为要解析的 xml 构建 DOM:parser.parse(new File("instance.xml"))。 validator 接受 Source,因此您可以:validator.validate(new StreamSource(new File("instance.xml")))。
    • 以这种方式工作,将在 xml 文件中的第一个错误时引发 SAXException,然后停止验证。但我想知道所有(!)错误。如果我改用ErrorHandler(实现ErrorHandler的自己的类),它会识别所有错误,但是validator.validate的try-catch-block不会抛出任何异常。我如何识别调用验证的类中的错误- 我的验证器的方法?感谢您的帮助!
    • 得承认,代码看起来比接受的答案更干净,更容易阅读。
    • 验证行缺少右括号。
    【解决方案3】:

    使用 Woodstox,配置 StAX 解析器以验证您的架构并解析 XML。

    如果捕获到异常,则 XML 无效,否则有效:

    // create the XSD schema from your schema file
    XMLValidationSchemaFactory schemaFactory = XMLValidationSchemaFactory.newInstance(XMLValidationSchema.SCHEMA_ID_W3C_SCHEMA);
    XMLValidationSchema validationSchema = schemaFactory.createSchema(schemaInputStream);
    
    // create the XML reader for your XML file
    WstxInputFactory inputFactory = new WstxInputFactory();
    XMLStreamReader2 xmlReader = (XMLStreamReader2) inputFactory.createXMLStreamReader(xmlInputStream);
    
    try {
        // configure the reader to validate against the schema
        xmlReader.validateAgainst(validationSchema);
    
        // parse the XML
        while (xmlReader.hasNext()) {
            xmlReader.next();
        }
    
        // no exceptions, the XML is valid
    
    } catch (XMLStreamException e) {
    
        // exceptions, the XML is not valid
    
    } finally {
        xmlReader.close();
    }
    

    注意:如果您需要验证多个文件,您应该尝试重复使用您的XMLInputFactory 和XMLValidationSchema 以最大限度地提高性能。

    【讨论】:

      【解决方案4】:

      针对在线模式进行验证

      Source xmlFile = new StreamSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("your.xml"));
      SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
      Schema schema = factory.newSchema(Thread.currentThread().getContextClassLoader().getResource("your.xsd"));
      Validator validator = schema.newValidator();
      validator.validate(xmlFile);
      

      针对本地架构进行验证

      Offline XML Validation with Java

      【讨论】:

        【解决方案5】:

        另一个答案:既然您说您需要验证您正在生成(写入)的文件,您可能希望在写入时验证内容,而不是先写入,然后再读取以进行验证.如果您使用基于 SAX 的编写器,您可能可以使用 JDK API 进行 Xml 验证:如果是这样,只需通过调用 'Validator.validate(source, result)' 链接验证器,其中源来自您的编写器,结果是输出需要去哪里。

        或者,如果您使用 Stax 编写内容(或使用或可以使用 stax 的库),Woodstox 也可以在使用 XMLStreamWriter 时直接支持验证。这是一个blog entry,展示了它是如何完成的:

        【讨论】:

        • 嘿 StaxMan,有没有可以进行漂亮打印缩进的 XMLStreamWriter?我很惊讶它不在标准实现中。另外,它有多大用处?我认为这是正确的方法,但似乎对此没有什么兴趣。
        • 刚刚在这里找到您关于 StaxMate 的帖子(但它不是 XMLStreamWriter):stackoverflow.com/questions/290326/stax-xml-formatting-in-java/…
        • 是的,StaxMate 可以做到。它在内部使用 XMLStreamWriter 来编写内容,因此您也可以通过这种方式连接验证器。
        【解决方案6】:

        使用 JAXB,您可以使用以下代码:

            @Test
        public void testCheckXmlIsValidAgainstSchema() {
            logger.info("Validating an XML file against the latest schema...");
        
            MyValidationEventCollector vec = new MyValidationEventCollector();
        
            validateXmlAgainstSchema(vec, inputXmlFileName, inputXmlSchemaName, inputXmlRootClass);
        
            assertThat(vec.getValidationErrors().isEmpty(), is(expectedValidationResult));
        }
        
        private void validateXmlAgainstSchema(final MyValidationEventCollector vec, final String xmlFileName, final String xsdSchemaName, final Class<?> rootClass) {
            try (InputStream xmlFileIs = Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlFileName);) {
                final JAXBContext jContext = JAXBContext.newInstance(rootClass);
                // Unmarshal the data from InputStream
                final Unmarshaller unmarshaller = jContext.createUnmarshaller();
        
                final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                final InputStream schemaAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsdSchemaName);
                unmarshaller.setSchema(sf.newSchema(new StreamSource(schemaAsStream)));
        
                unmarshaller.setEventHandler(vec);
        
                unmarshaller.unmarshal(new StreamSource(xmlFileIs), rootClass).getValue(); // The Document class is the root object in the XML file you want to validate
        
                for (String validationError : vec.getValidationErrors()) {
                    logger.trace(validationError);
                }
            } catch (final Exception e) {
                logger.error("The validation of the XML file " + xmlFileName + " failed: ", e);
            }
        }
        
        class MyValidationEventCollector implements ValidationEventHandler {
            private final List<String> validationErrors;
        
            public MyValidationEventCollector() {
                validationErrors = new ArrayList<>();
            }
        
            public List<String> getValidationErrors() {
                return Collections.unmodifiableList(validationErrors);
            }
        
            @Override
            public boolean handleEvent(final ValidationEvent event) {
                String pattern = "line {0}, column {1}, error message {2}";
                String errorMessage = MessageFormat.format(pattern, event.getLocator().getLineNumber(), event.getLocator().getColumnNumber(),
                        event.getMessage());
                if (event.getSeverity() == ValidationEvent.FATAL_ERROR) {
                    validationErrors.add(errorMessage);
                }
                return true; // you collect the validation errors in a List and handle them later
            }
        }
        

        【讨论】:

          【解决方案7】:

          Java 运行时库支持验证。上次我检查这是幕后的 Apache Xerces 解析器。您可能应该使用javax.xml.validation.Validator。

          import javax.xml.XMLConstants;
          import javax.xml.transform.Source;
          import javax.xml.transform.stream.StreamSource;
          import javax.xml.validation.*;
          import java.net.URL;
          import org.xml.sax.SAXException;
          //import java.io.File; // if you use File
          import java.io.IOException;
          ...
          URL schemaFile = new URL("http://host:port/filename.xsd");
          // webapp example xsd: 
          // URL schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
          // local file example:
          // File schemaFile = new File("/location/to/localfile.xsd"); // etc.
          Source xmlFile = new StreamSource(new File("web.xml"));
          SchemaFactory schemaFactory = SchemaFactory
              .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
          try {
            Schema schema = schemaFactory.newSchema(schemaFile);
            Validator validator = schema.newValidator();
            validator.validate(xmlFile);
            System.out.println(xmlFile.getSystemId() + " is valid");
          } catch (SAXException e) {
            System.out.println(xmlFile.getSystemId() + " is NOT valid reason:" + e);
          } catch (IOException e) {}
          

          架构工厂常量是定义 XSD 的字符串 http://www.w3.org/2001/XMLSchema。上面的代码根据 URL http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd 验证 WAR 部署描述符,但您也可以轻松地针对本地文件进行验证。

          您不应该使用 DOMParser 来验证文档(除非您的目标是无论如何创建文档对象模型)。这将在解析文档时开始创建 DOM 对象 - 如果您不打算使用它们,那就太浪费了。

          【讨论】:

          • 在这个例子中你使用的是 DOM 还是 SAX 解析器?我怎么知道你正在使用哪个解析器,因为我看不到对任何一个的引用。
          • @ziggy - 这是JAXP implementation 的实现细节。 Sun 的 JDK 6 使用带有 StreamSource 的 SAX 解析器。在这种情况下,JAXP 实现可以合法地使用 DOM 解析器,但没有理由这样做。如果你 use a DOM parser 显式验证,你肯定会实例化一个 DOM 树。
          • 如何在上面使用 ErrorHandler?是否只是创建 ErrorHandler 并将其与验证器相关联?即 validator.SetErrorHandler() ,如此 SO 问题 stackoverflow.com/questions/4864681/…? 中的示例
          • 不应该将执行只用于执行情况而不用于控制流吗?
          • 这段代码不会只捕获致命错误吗?如果您希望能够捕获非致命事件(例如非结构性事件),我认为您需要使用 ErrorHandler。
          【解决方案8】:

          以下是使用Xerces2 的方法。这方面的教程,here(需要注册)。

          原文出处:公然抄自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.");
               }
            }
          }
          

          【讨论】:

          • SAX 解析器会更高效——DOM 解析器创建 DOM 对象;在这种情况下是浪费的操作。
          • 问题是针对 XSD 验证 XML。在这个答案中,您将更进一步并获得一个不需要的 Parser 对象,对吧?
          • “ErrorChecker 无法解析为类型”.. 缺少导入?
          【解决方案9】:

          如果你有一台 Linux 机器,你可以使用免费的命令行工具 SAXCount。我发现这非常有用。

          SAXCount -f -s -n my.xml
          

          它针对 dtd 和 xsd 进行验证。 50MB 文件需要 5 秒。

          在 Debian Squeeze 中,它位于包“libxerces-c-samples”中。

          dtd 和 xsd 的定义必须在 xml 中!您不能单独配置它们。

          【讨论】:

          • 这允许从 vim 进行简单的 XML 验证 (:!SAXCount -f -n -s %)
          • 或使用古老的 xmllint xmllint --schema phone.xsd phone.xml(来自 13ren 的回答)
          • superuser.com 的好答案
          【解决方案10】:

          我们使用 ant 构建我们的项目,因此我们可以使用 schemavalidate 任务来检查我们的配置文件:

          <schemavalidate> 
              <fileset dir="${configdir}" includes="**/*.xml" />
          </schemavalidate>
          

          现在顽皮的配置文件将导致我们的构建失败!

          http://ant.apache.org/manual/Tasks/schemavalidate.html

          【讨论】:

            【解决方案11】:

            如果您以编程方式生成 XML 文件,您可能需要查看 XMLBeans library。使用命令行工具,XMLBeans 将自动生成并打包一组基于 XSD 的 Java 对象。然后,您可以使用这些对象来构建基于此架构的 XML 文档。

            它内置了对模式验证的支持,并且可以将 Java 对象转换为 XML 文档,反之亦然。

            Castor 和 JAXB 是其他 Java 库,它们的用途与 XMLBeans 类似。

            【讨论】:

              【解决方案12】:

              我只需要针对 XSD 验证 XML 一次,所以我尝试了 XMLFox。我发现它非常混乱和奇怪。帮助说明似乎与界面不匹配。

              我最终使用了 LiquidXML Studio 2008 (v6),它更易于使用且更加熟悉(用户界面与我经常使用的 Visual Basic 2008 Express 非常相似)。缺点:免费版没有验证能力,所以只能试用30天。

              【讨论】:

              • 问题是Java,但这个答案不是。 :-(
              • 公平地说,“java”这个词从来没有出现在问题中,只是标签。我会为此提出问题,而不是答复。
              • 感谢 james 和 Mark,帮我磨练一下!
              【解决方案13】:

              您在寻找工具还是库?

              就库而言,事实上的标准几乎是Xerces2,它同时具有C++ 和Java 版本。

              请注意,这是一个重量级的解决方案。但话又说回来,针对 XSD 文件验证 XML 是一个相当繁重的问题。

              至于为您执行此操作的工具,XMLFox 似乎是一个不错的免费软件解决方案,但我不能确定没有亲自使用它。

              【讨论】:

                猜你喜欢
                • 2018-10-09
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2016-10-19
                相关资源
                最近更新 更多