Web上有許多關於此驗證過程的手冊。儘管如此,我無法找到我的代碼無法正常工作的原因。輸入模式和XML的值我得到here。使用XMLReader驗證XML與XSD
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'.
在調試模式似乎一切都很好。架構設置正確,依此類推。想法?
可能是它的命名空間的問題你的架構有目標命名空間,所以你可以像trysomething <注的xmlns =「http://www.java2s.com」> – 2012-08-16 15:28:08
@ KonstantinV.Salikhov沒有變化,但您的建議適用於Validator使用。 – Steve 2012-08-16 16:44:12