웹에서이 유효성 검사 절차에 대한 많은 설명서가 있습니다. 이 사실에도 불구하고 내 코드가 적절한 방식으로 작동하지 않는 이유를 찾을 수 없습니다. 입력 스키마와 XML의 값은 here입니다.XMLReader를 사용하여 XSD에 대해 XML 유효성 검사
[Error] :1:28: cvc-elt.1: Cannot find the declaration of element 'note'.
디버거 모드에서 모든 것이 잘 될 것 같다 :
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();
}
실행 결과는 다음과 같은 것입니다. 스키마가 올바르게 설정되어 있습니다. 아이디어?
이 될 수는 공간의 문제입니다 당신이 <노트의 xmlns = "http://www.java2s.com"> –
@ KonstantinV.Salikhov 변경없이 같은 trysomething 수 있도록 귀하의 스키마를 대상 네임 스페이스가 있지만, 귀하의 제안은 Validator 사용법과 관련이 있습니다. – Steve