使用Free XML Validator验证XML w.r.t XSD的最佳方法是什么?

时间:2009-10-12 19:44:35

标签: java xml xsd xml-validation

我需要针对XSD验证XML,因此可用的免费XML Validator对我的任务有用。

感谢。

1 个答案:

答案 0 :(得分:1)

xerces包含Java,C ++和Perl版本。

为方便起见,perl版本包含一个命令行验证器。

Java版API包括validation

的类和示例代码

示例代码:

// parse an XML document into a DOM tree
DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance();
parserFactory.setNamespaceAware(true);
DocumentBuilder parser = parserFactory.newDocumentBuilder();
Document document = parser.parse(new File("instance.xml"));

// 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 DOMSource(document));
} catch (SAXException e) {
    // instance document is invalid!
}