2012-08-16 7 views
2

웹에서이 유효성 검사 절차에 대한 많은 설명서가 있습니다. 이 사실에도 불구하고 내 코드가 적절한 방식으로 작동하지 않는 이유를 찾을 수 없습니다. 입력 스키마와 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(); 
    } 

실행 결과는 다음과 같은 것입니다. 스키마가 올바르게 설정되어 있습니다. 아이디어?

+1

이 될 수는 공간의 문제입니다 당신이 <노트의 xmlns = "http://www.java2s.com"> –

+0

@ KonstantinV.Salikhov 변경없이 같은 trysomething 수 있도록 귀하의 스키마를 대상 네임 스페이스가 있지만, 귀하의 제안은 Validator 사용법과 관련이 있습니다. – Steve

답변

2

문제는 XML에서 정의되지 않은 네임 스페이스입니다. ?

static String xmlString = "<?xml version=\"1.0\"?>" + 
    "<note xmlns=\"http://www.java2s.com\">" + 
    "<to>rtoName</to>" + 
    "<from>FromName</from>" + 
    "<heading>Info</heading>" + 
    "<body>Message Body</body>" + 
    "</note>"; 
+0

아니요, 작동하지 않습니다. 여전히 같은 오류. 이유가 궁금합니다. – Steve

+0

나는 그 이유를 발견하고 다음 세대를 위해 여기에 그것을 쓸 것이다 :) 반드시 method-spf.setNamespaceAware (true)로 SAXParserFactory를 수동으로 네임 스페이스를 인식하도록 설정해야한다. 나는이 과정이 이미 Validator API 내부에서 이루어 졌으므로 필요하지 않다고 생각한다. 정말 유용한 도움을 주셔서 감사합니다. – Steve

2

당신은 내가 또 다른 방법을 제시하고 싶습니다 XMLReader
을 사용하는 이유는 특별한 이유가, 당신이 찾을 수 있습니다 : 네임 스페이스를 명시 적으로 설정하는

봅니다 (당신의 targetNamespace XSD에서 볼 유용 :?

import javax.xml.validation.Schema; 
import javax.xml.validation.SchemaFactory; 
import javax.xml.validation.Validator;  

// ... 

    try { 
     // load schema from file 
     File schemaFile = new File(schemaLocation); 
     // load xml source form string holding the content 
     Source xmlFile = new StreamSource(new StringReader(fileContent)); 

     SchemaFactory schemaFactory = SchemaFactory 
      .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 

     Schema schema = schemaFactory.newSchema(schemaFile); 

     Validator validator = schema.newValidator(); 

     validator.validate(xmlFile); 

     System.out.println("XML is valid"); 

    } catch (Exception e) { 

     System.out.println("XML is NOT valid"); 
     System.out.println("Reason: " + e.getMessage()); 

    } 
+0

답변을 주셔서 감사합니다. 시도했지만 작동하지 않습니다. 그러나 Konstantin과 DRCB의 제안으로 마침내 작동합니다! – Steve

+0

이 방법은 나를 위해 일했습니다 ... – rogerdpack

관련 문제