JAXP:如何针对XML Schema验证org.w3c.dom.Document

时间:2022-10-30 13:44:36

How to validate an (already parsed) org.w3c.dom.Document against a XML Schema using JAXP?

如何使用JAXP针对XML Schema验证(已解析的)org.w3c.dom.Document?

1 个解决方案

#1


12  

You can use the javax.xml.validation APIs for this.

您可以使用javax.xml.validation API。

SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
URL schemaURL = // The URL to your XML Schema; 
Schema schema = sf.newSchema(schemaURL); 
Validator validator = schema.newValidator();
DOMSource source = new DOMSource(xmlDOM);
validator.validate(source);

The example below demonstrates how to validate a JAXB object model against a schema, but you'll see it's easy to replace the JAXBSource with a DOMSource for DOM:

下面的示例演示了如何针对模式验证JAXB对象模型,但您会发现使用DOM的DOMSource替换JAXBSource很容易:

#1


12  

You can use the javax.xml.validation APIs for this.

您可以使用javax.xml.validation API。

SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
URL schemaURL = // The URL to your XML Schema; 
Schema schema = sf.newSchema(schemaURL); 
Validator validator = schema.newValidator();
DOMSource source = new DOMSource(xmlDOM);
validator.validate(source);

The example below demonstrates how to validate a JAXB object model against a schema, but you'll see it's easy to replace the JAXBSource with a DOMSource for DOM:

下面的示例演示了如何针对模式验证JAXB对象模型,但您会发现使用DOM的DOMSource替换JAXBSource很容易: