android怎么用Schema验证xml
发布网友
发布时间:2022-04-19 07:52
我来回答
共1个回答
热心网友
时间:2022-04-19 09:21
这里解决下方案如下:
[note.xml]
Xml代码
<?xml version="1.0"?>
<note xmlns="
<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代码
<?xml version="1.0"?>
<xs:schema xmlns:xs=""
targetNamespace="/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]
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);
转载,仅供参考。