如何在给定XSD架构的情况下验证Java中的XML?
答案 0 :(得分:3)
尝试以下方法:
File schemaFile = new File("schema.xsd");
File xmlFile = new File("input.xml");
Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(new StreamSource(new FileInputStream(xmlFile)));
答案 1 :(得分:0)
有许多关于如何通过快速搜索执行此操作的示例。以下是使用JaxP的Java Ranch中的一个:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setAttribute(
"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
factory.setAttribute(
"http://java.sun.com/xml/jaxp/properties/schemaSource",
"http://domain.com/mynamespace/mySchema.xsd");
Document doc = null;
try{
DocumentBuilder parser = factory.newDocumentBuilder();
doc = parser.parse("data.xml");
}
catch (ParserConfigurationException e){
System.out.println("Parser not configured: " + e.getMessage());
}
catch (SAXException e){
System.out.print("Parsing XML failed due to a " + e.getClass().getName() + ":");
System.out.println(e.getMessage());
}
catch (IOException e){
e.printStackTrace();
}