网上有很多关于这个验证过程的手册。尽管如此,我还是找不到我的代码无法正常工作的原因。我在这里得到的输入模式和 xml 的值。
static String schemaString ="<?xml version=\"1.0\"?>" +
"<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"" +
" targetNamespace=\"http://www.java2s.com\"" +
" xmlns=\"http://www.java2s.com\"" +
" 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>";
static String xmlString = "<?xml version=\"1.0\"?>" +
"<note>" +
"<to>rtoName</to>" +
"<from>FromName</from>" +
"<heading>Info</heading>" +
"<body>Message Body</body>" +
"</note>";
String xml;
XMLReader xmlReader = null;
try {
SAXSource source = new SAXSource(new InputSource(new StringReader(schemaString)));
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(source);
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setSchema(schema);
SAXParser saxParser = spf.newSAXParser();
xmlReader = saxParser.getXMLReader();
} catch (Exception e) {
e.printStackTrace();
}
// parsing step after all preconditions succeeded
try {
xmlReader.parse(new InputSource(new StringReader(xmlString)));
} catch (Exception e) {
e.printStackTrace();
}
执行结果是这样的:
[Error] :1:28: cvc-elt.1: Cannot find the declaration of element 'note'.
在调试器模式下,一切似乎都很好。架构设置正确等等。想法?