[英]How to validate in Java a XML with XSD schema
給定XSD架構,如何在Java中驗證XML?
請嘗試以下操作:
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)));
關於如何通過快速搜索執行此操作的示例很多。 這是Java Ranch中使用JaxP的一個:
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.