2009-11-10 4 views
9

XmlSerializer를 사용하여 XML 컨테이너를 deserialize하고 있습니다. 하지만 xsd.exe 클래스는 xml을 읽을 수있는 기능 만 제공했지만 유효성은 확인하지 못했습니다. 예를 들어, 한 노드가 문서에서 누락 된 경우 생성 된 클래스의 속성 필드는 예상 한대로 유효성 검사 예외를 throw하지 않고 null이됩니다. 어떻게하면 될까요? 감사!xmlserializer 유효성 검사

답변

26

다음 코드는 역 직렬화 중에 스키마에 대해 유효성을 검사해야합니다. 직렬화하는 동안 스키마에 대해 유효성을 검사하는데도 비슷한 코드를 사용할 수 있습니다.

private static Response DeserializeAndValidate(string tempFileName) 
{ 
    XmlSchemaSet schemas = new XmlSchemaSet(); 
    schemas.Add(LoadSchema()); 

    Exception firstException = null; 

    var settings = new XmlReaderSettings 
        { 
         Schemas = schemas, 
         ValidationType = ValidationType.Schema, 
         ValidationFlags = 
          XmlSchemaValidationFlags.ProcessIdentityConstraints | 
          XmlSchemaValidationFlags.ReportValidationWarnings 
        }; 
    settings.ValidationEventHandler += 
     delegate(object sender, ValidationEventArgs args) 
     { 
      if (args.Severity == XmlSeverityType.Warning) 
      { 
       Console.WriteLine(args.Message); 
      } 
      else 
      { 
       if (firstException == null) 
       { 
        firstException = args.Exception; 
       } 

       Console.WriteLine(args.Exception.ToString()); 
      } 
     }; 

    Response result; 
    using (var input = new StreamReader(tempFileName)) 
    { 
     using (XmlReader reader = XmlReader.Create(input, settings)) 
     { 
      XmlSerializer ser = new XmlSerializer(typeof (Response)); 
      result = (Response) ser.Deserialize(reader); 
     } 
    } 

    if (firstException != null) 
    { 
     throw firstException; 
    } 

    return result; 
} 
+2

이 솔루션을 공유해 주셔서 감사합니다. 이렇게하면 XmlReader를 통해 유효성을 검사하여 deserialize와 함께 유효성 검사를 수행하므로 더 나은 방법입니다. – el2iot2

4

다음 코드는 수동으로 스키마 파일에 대해 XML을로드하고 유효성을 검사하여 프로그래밍 방식으로 resulting errors and/or warnings을 처리 할 수 ​​있도록합니다.

//Read in the schema document 
using (XmlReader schemaReader = XmlReader.Create("schema.xsd")) 
{ 
    XmlSchemaSet schemaSet = new XmlSchemaSet(); 

    //add the schema to the schema set 
    schemaSet.Add(XmlSchema.Read(schemaReader, 
    new ValidationEventHandler(
     delegate(Object sender, ValidationEventArgs e) 
     { 
     }  
    ))); 

    //Load and validate against the programmatic schema set 
    XmlDocument xmlDocument = new XmlDocument(); 
    xmlDocument.Schemas = schemaSet; 
    xmlDocument.Load("something.xml"); 

    xmlDocument.Validate(new ValidationEventHandler(
     delegate(Object sender, ValidationEventArgs e) 
     { 
      //Report or respond to the error/warning 
     } 
    )); 
} 

지금 분명 당신은이 작업을 자동으로 수행하는 xsd.exe에 의해 생성 된 클래스를 가지고 원하는 및로드하는 동안 (위의 접근 방식은 XML 파일의 두 번째 처리를 필요로)하지만, 전 부하 유효성을 허용 것 조작 된 입력 파일을 프로그래밍 방식으로 감지 할 수 있습니다.

+0

@ 존 손더스 - I 클래스 생성 코드가 곧 작동 언제든지 변경 될 수 있음을 의심하고, 그리고 MSDN 사이트 xsd.exe에 대한 관련 옵션을 보여줍니다, 그래서 나는 제안하는 것이 합리적이라고 생각 해결 방법 ... – el2iot2

+1

질문 텍스트에서 OP는 잘못된 입력 XML에 대해 예외가 throw되기를 원한다고 표현합니다. 이 방법은이를 달성합니다. 나는 이것이 이것이 할 수있는 유일한 방법이라고 주장하지 않으며, 그것이 최선의 방법이라고 주장하지도 않습니다. 그러나 나는 과거에 일반적으로 XML 문서의 유효성을 검사하는 데 사용한 방식을 사용하여 응답했습니다. – el2iot2

관련 문제