2012-08-24 4 views
2

일부 XML의 유효성을 검사하기 위해 클래스를 만들었습니다. 해당 클래스 내에서 유효성 검사 메소드가 있습니다. 내 XML 스키마가 포함 된 .xsd 파일도 있습니다. 이 파일을 사용하려면 xsd 파일을 문자열로로드해야한다고 들었습니다.유효성 검사 메서드에서 .xsd 파일 사용

xsd 파일을 문자열로로드하는 방법은 무엇입니까? 이 당신의 탐구에 도움이

string schema; 
using(StreamReader file = new StreamReader(path) 
{ 
    schema = file.ReadToEnd(); 
} 

희망 :

+0

그래서 XML과 XSD 파일이 분리되어 있으며 XSD를 사용하여 XML의 유효성을 검사하겠습니까? – psubsee2003

+0

@ psubsee2003 예, 내 xml 데이터가 서버에서 가져옵니다. –

답변

0

문자열로 전체 파일을 읽을 매우 쉽습니다.

2

당신은 당신이 더 컨텍스트없이 위해 StreamReader 및 ReadToEnd

2

을 사용할 수 있습니다로드하려면이 코드

 XmlReaderSettings settings = new XmlReaderSettings(); 
     settings.Schemas.Add("....", "youXsd.xsd"); 
     settings.ValidationType = ValidationType.Schema; 
     settings.ValidationEventHandler += new ValidationEventHandler(YourSettingsValidationEventHandler); 

     XmlReader books = XmlReader.Create("YouFile.xml", settings); 

     while (books.Read()) { } 


     //Your validation 
     static void YourSettingsValidationEventHandler(object sender, ValidationEventArgs e) 
     { 

     } 

2 시도 할 수 있습니다, 나는 Load the xsd file into a string 실제로 무엇을 의미하는지 잘 모른다, 그러나 멀리있다 XML을 검증하는 간단한 메소드.

var xDoc = XDocument.Load(xmlPath); 
var set = new XmlSchemaSet(); 

using (var stream = new StreamReader(xsdPath)) 
{ 
    // the null here is a validation call back for the XSD itself, unless you 
    // specifically want to handle XSD validation errors, I just pass a null and let 
    // an exception get thrown as there usually isn't much you can do with an error in 
    // the XSD itself 
    set.Add(XmlSchema.Read(stream, null));     
} 

xDoc.Validate(set, ValidationCallBack); 

그런 다음 당신은 그냥 유효성 검사 오류에 대한 핸들러로 클래스에 ValidationCallBack라는 방법이 필요합니다 (당신은 Validate() 방법은 위의이 방법을 참조하는 매개 변수 당신이 원하는대로 그것을 이름 만 위임 할 수 있습니다) :

public void ValidationCallBack(object sender, ValidationEventArgs e) 
{ 
    // do something with any errors 
}