以前验证XML一直使用dtd的,今天尝试着用xsd作验证,可是网上的例子一直跑不起来。折腾了半天才发现是例子里面对于XML文件的命名空间没有设置清楚,这里解决下方案记录:
[note.xml]
<?xml version="1.0"?> <note xmlns="http://adcoup.baidu.com/schema/note"> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
网上的例子就是在这里没设置对xmlns,这里的xmlns一定要和下面note.xsd中的targetNamespace和xmlns一致
[note.xsd]
<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://adcoup.baidu.com/schema/note" xmlns="http://adcoup.baidu.com/schema/note" elementFormDefault="qualified"> <xs:element name="note"> <xs:complexType> <xs:sequence> <xs:element name="to" type="xs:string" /> <xs:element name="from" type="xs:string" /> <xs:element name="heading" type="xs:string" /> <xs:element name="body" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
[java]
String configFileLocation = "/note.xml";
String xsdFileLocation = "/note.xsd";
InputStream configInputStream = this.getClass().getResourceAsStream(configFileLocation);
if (configInputStream == null) {
throw new IllegalArgumentException("can not find resource[" + configFileLocation + "]");
}
InputStream xsdInputStream = this.getClass().getResourceAsStream(xsdFileLocation);
if (xsdInputStream == null) {
throw new IllegalArgumentException("can not find resource[" + xsdFileLocation + "]");
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new SAXSource(new InputSource(xsdInputStream)));
factory.setSchema(schema);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
@Override
public void warning(SAXParseException exception) throws SAXException {
throw new RuntimeException(exception);
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
throw new RuntimeException(exception);
}
@Override
public void error(SAXParseException exception) throws SAXException {
throw new RuntimeException(exception);
}
});
document = builder.parse(configInputStream);
System.out.println(document);