我正在生成一些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.");
     }
  }
}

其他回答

使用Java 7,您可以遵循包描述中提供的文档。

// 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! }

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

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

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

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

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

我最终使用了LiquidXML Studio 2008 (v6),它更容易使用,也更熟悉(UI与我经常使用的Visual Basic 2008 Express非常相似)。缺点:免费版没有验证功能,所以我不得不使用30天的试用期。

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

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

现在淘气的配置文件将失败我们的构建!

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

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