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


当前回答

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

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

Castor和JAXB是其他Java库,其功能与XMLBeans类似。

其他回答

下面是如何使用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.");
     }
  }
}

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

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

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

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

对在线模式进行验证

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验证

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

SAXCount -f -s -n my.xml

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

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

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

使用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! }