XmlSerializer를 사용하여 XML 컨테이너를 deserialize하고 있습니다. 하지만 xsd.exe 클래스는 xml을 읽을 수있는 기능 만 제공했지만 유효성은 확인하지 못했습니다. 예를 들어, 한 노드가 문서에서 누락 된 경우 생성 된 클래스의 속성 필드는 예상 한대로 유효성 검사 예외를 throw하지 않고 null이됩니다. 어떻게하면 될까요? 감사!xmlserializer 유효성 검사
답변
다음 코드는 역 직렬화 중에 스키마에 대해 유효성을 검사해야합니다. 직렬화하는 동안 스키마에 대해 유효성을 검사하는데도 비슷한 코드를 사용할 수 있습니다.
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;
}
다음 코드는 수동으로 스키마 파일에 대해 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 파일의 두 번째 처리를 필요로)하지만, 전 부하 유효성을 허용 것 조작 된 입력 파일을 프로그래밍 방식으로 감지 할 수 있습니다.
@ 존 손더스 - I 클래스 생성 코드가 곧 작동 언제든지 변경 될 수 있음을 의심하고, 그리고 MSDN 사이트 xsd.exe에 대한 관련 옵션을 보여줍니다, 그래서 나는 제안하는 것이 합리적이라고 생각 해결 방법 ... – el2iot2
질문 텍스트에서 OP는 잘못된 입력 XML에 대해 예외가 throw되기를 원한다고 표현합니다. 이 방법은이를 달성합니다. 나는 이것이 이것이 할 수있는 유일한 방법이라고 주장하지 않으며, 그것이 최선의 방법이라고 주장하지도 않습니다. 그러나 나는 과거에 일반적으로 XML 문서의 유효성을 검사하는 데 사용한 방식을 사용하여 응답했습니다. – el2iot2
- 1. ASP에서 유효성 검사/유효성 검사 유효성 검사 .net MVC 3
- 2. Html.DropDownList 유효성 검사 오류가없는 유효성 검사 오류
- 3. jQuery submitHandler 트리거 유효성 검사 유효성 검사
- 4. 사용자 지정 입력란에서 유효성 검사/유효성 검사 이벤트가 발생하지 않도록합니다.
- 5. 로그인 유효성 검사 + IP 주소 유효성 검사 PHP에서
- 6. Silverlight 유효성 검사. 전자 메일 유효성 검사 관련 문제
- 7. 플래시 폼 유효성 검사 : ComboBox 유효성 검사 : AS3 : 플래시 CS3
- 8. WPF의 여러 유효성 검사 규칙 및 유효성 검사 템플릿
- 9. Silverlight 유효성 검사 - 유효성 검사 메시지 자동 표시
- 10. Struts2 유효성 검사 - 입력에 대한 유효성 검사 없음
- 11. JQuery 유효성 검사 플러그인 유효성 검사 후 제출 다시 허용
- 12. 체크 박스 및 aspnet 유효성 검사 유효성 검사
- 13. 라이브 Jquery 폼 유효성 검사 및 CakePHP 유효성 검사
- 14. jquery 유효성 검사 프레임 워크를 사용하여 이름 유효성 검사
- 15. 유효성 검사 오류 : "유효성 검사 실패 :"를 제거하는 방법?
- 16. 개체 수집시 사용자 지정 유효성 검사 또는 제거 유효성 검사
- 17. XML 스키마 유효성 검사 - 필드 내 유효성 검사
- 18. 고급 JQuery 유효성 검사 : 특정 조건에 대한 유효성 검사 방지
- 19. jQuery 유효성 검사 - 핵심 유효성 검사 메소드 덮어 쓰기
- 20. 엔터프라이즈 라이브러리 유효성 검사 블록을 사용하여 복잡한 개체 유효성 검사
- 21. 도메인 개체 유효성 검사 및 유효성 검사 결과 표시
- 22. Ajax 양식 유효성 검사
- 23. 날짜 유효성 검사
- 24. JQuery와 유효성 검사 플러그인
- 25. 유효성 검사 단추 문제
- 26. jquery 유효성 검사 규칙
- 27. Gridview 유효성 검사
- 28. JQuery에서 조건부 유효성 검사
- 29. Silverlight에서 유효성 검사
- 30. ASP.NET 페이지 유효성 검사
이 솔루션을 공유해 주셔서 감사합니다. 이렇게하면 XmlReader를 통해 유효성을 검사하여 deserialize와 함께 유효성 검사를 수행하므로 더 나은 방법입니다. – el2iot2