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

前端 未结 13 1329
滥情空心
滥情空心 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条回答
  •  旧时难觅i
    2020-11-22 08:33

    Using Woodstox, configure the StAX parser to validate against your schema and parse the XML.

    If exceptions are caught the XML is not valid, otherwise it is valid:

    // 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();
    }
    

    Note: If you need to validate multiple files, you should try to reuse your XMLInputFactory and XMLValidationSchema in order to maximize the performance.

提交回复
热议问题