What's the best way to validate an XML file against an XSD file?

前端 未结 13 1294
滥情空心
滥情空心 2020-11-22 07:37

I\'m generating some xml files that needs to conform to an xsd file that was given to me. What\'s the best way to verify they conform?

13条回答
  •  清酒与你
    2020-11-22 08:18

    Using Java 7 you can follow the documentation provided in package description.

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

提交回复
热议问题