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

前端 未结 13 1578
滥情空心
滥情空心 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:17

    Validate against online schemas

    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);
    

    Validate against local schemas

    Offline XML Validation with Java

提交回复
热议问题