我正在生成一些xml文件,需要符合xsd文件给我。我该如何验证它们是否一致?


当前回答

下面是如何使用Xerces2来实现这一点。这方面的教程在这里(req。注册)。

原始出处:公然抄袭:

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

其他回答

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

SAXCount -f -s -n my.xml

它针对dtd和xsd进行验证。 5s,一个50MB的文件。

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

dtd和xsd的定义必须在xml中!你不能分别配置它们。

使用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,以最大化性能。

你是在找工具还是图书馆?

至于库,实际上的标准是Xerces2,它有c++和Java两个版本。

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

XMLFox似乎是一个不错的免费解决方案,但没有亲身使用过,我不敢肯定。

对在线模式进行验证

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

对本地模式进行验证

使用Java进行离线XML验证

还有一个答案:既然您说过需要验证正在生成(写入)的文件,那么您可能希望在写入时验证内容,而不是先写入,然后再读取以进行验证。如果你使用的是基于sax的writer,你也可以使用JDK API进行Xml验证:如果是这样,只需调用' validator '来链接验证器。Validate (source, result)',其中source来自你的作者,result是输出需要去的地方。

或者,如果使用Stax来编写内容(或者使用或可以使用Stax的库),Woodstox也可以在使用XMLStreamWriter时直接支持验证。下面是一篇博客文章,展示了如何做到这一点: