2010-01-21 2 views
3

사용자가 XML 파일로 데이터를 내보낼 수 있기를 바랍니다. 물론 나중에 같은 XML 파일을 가져올 수 있기를 원하지만 항상 XML 파일을 변경하거나 다른 XML 파일이 될 수 있습니다..NET을 통해 XML 코드 파일의 유효성을 검사하는 방법은 무엇입니까? + XML 직렬화를 사용하면 어떻게됩니까?

XML 파일이 올바른 형식인지 확인하려면 유효성을 검사하고 싶습니다. 그래서 나는 코드를 통해 이루어져야한다는 것을 확인하기 위해 스키마와 같은 것이 필요할 것이라고 생각합니다.

그래서

<Root> 
<Something> 
    <SomethingElse> </SomethingElse> 
</Something> 
</Root> 

을 기대한다면 나는 다른 포맷 후 다른 파일 내가 기대 한 싶지 않아.

어떻게 입력란의 유효성을 검사합니까? 마찬가지로 태그 사이에 텍스트가 있어야한다고 말합니다. 비어 있으면 파일이 유효하지 않습니다.

어떻게하면됩니까?

편집 나는 그것이 잘못된 형식 인 경우 그래서 예외 통해 것 알고 XML 직렬화를 사용하여 작동하지 않는 물건을 무시하기로 결정했다. 그러나 난 그냥 그것을 통해 C# 각 레코드의 유효성을 검사해야 또는 내가 그것을 할 xml 스키마를 만들어야할지 잘 모르겠습니다.

xml serialization을 사용하여 xml 스키마를 통해 원하는 경우 어떻게 작동합니까? 마치 내가 응답에서 본 것과 같은 것을 먼저 할 것인가? 또는 나는 그것을 어떻게 할 것이냐?

답변

10

는 코드의 그 그렇게하기 위해 사용할 수 있습니다 :

using (FileStream stream = File.OpenRead(xsdFilepath)) 
{ 
    XmlReaderSettings settings = new XmlReaderSettings(); 

    XmlSchema schema = XmlSchema.Read(stream, OnXsdSyntaxError); 
    settings.ValidationType = ValidationType.Schema; 
    settings.Schemas.Add(schema); 
    settings.ValidationEventHandler += OnXmlSyntaxError; 

    using (XmlReader validator = XmlReader.Create(xmlPath, settings)) 
    { 
     // Validate the entire xml file 
     while (validator.Read()) ; 
    } 
} 

구문 오류가 발생하면 OnXmlSyntaxError 함수가 호출됩니다.

9

XML 파일의 유효성을 검사하는 몇 가지 방법이 있습니다. Validating an XML against Referenced XSD in C# 예를 참조하세요 또한 How To Validate an XML Document by Using DTD, XDR, or XSD in Visual C# .NET

또 다른 좋은 예는 다음

Validate XML against XSD using code at runtime in C#이 마지막 게시물에서 코드입니다 :

public void ValidateXmlDocument(
    XmlReader documentToValidate, string schemaPath) 
{ 
    XmlSchema schema; 
    using (var schemaReader = XmlReader.Create(schemaPath)) 
    { 
     schema = XmlSchema.Read(schemaReader, ValidationEventHandler); 
    } 

    var schemas = new XmlSchemaSet(); 
    schemas.Add(schema); 

    var settings = new XmlReaderSettings(); 
    settings.ValidationType = ValidationType.Schema; 
    settings.Schemas = schemas; 
    settings.ValidationFlags = 
     XmlSchemaValidationFlags.ProcessIdentityConstraints | 
     XmlSchemaValidationFlags.ReportValidationWarnings; 
    settings.ValidationEventHandler += ValidationEventHandler; 

    using (var validationReader = XmlReader.Create(documentToValidate, 
      settings)) 
    { 
     while (validationReader.Read()) { } 
    } 
} 

private static void ValidationEventHandler(
    object sender, ValidationEventArgs args) 
{ 
    if (args.Severity == XmlSeverityType.Error) 
    { 
     throw args.Exception; 
    } 
    Debug.WriteLine(args.Message); 
} 
다음
0
당신은 당신의 클래스에서 XML 직렬화를 사용할 수 있습니다

:

[XmlType("Root", Namespace = "http://example.com/Root")] 
[XmlRoot(Namespace = "http://example.com/Root.xsd", ElementName = "Root", IsNullable = false)] 
public class Root { 
    [XmlElement("Something")] 
    public Something Something { get; set; } 
} 

public class Something { 
    [XmlElement("SomethingElse")] 
    public SomethingElse SomethingElse { get; set; } 
} 

public class SomethingElse { 
    [XmlText] 
    public string Text { get; set; } 
} 

이처럼 직렬화 :

var serializer = new XmlSerializer(typeof(Root)); 
serializer.Serialize(outputStrem, myRoot); 

그런 다음 deserializing 전에 테스트 할 수 있습니다.:

var serializer = new XmlSerializer(typeof(Root)); 
string xml = @" 
    <Root xmlns='http://example.com/Root'> 
    <Something> 
     <SomethingElse>Yep!</SomethingElse> 
    </Something> 
    </Root>"; // remember to use the XML namespace! 
Debug.Assert(serializer.CanDeserialize(new XmlTextReader(new StringReader(xml)))); 

그리고 단순히 역 직렬화하기 :

Root newRoot = (Root)serializer.Deserialize(inputStream); 

귀하의 XSD는 암시이다. 수업과 일치합니다. 더 풍부한 XSD를 사용하려면 Schema Providers으로 모험 할 수 있습니다.

+0

그래서 "xml"문자열을 스키마 제공자로 사용하여 확인하십시오. 그러나 내가 원한다면 XSD를 만들고 필수 필드를 원할 수 있습니까? – chobo2

+0

아니요, XML 문자열이 스키마가 아니므로 유효성을 검사하려는 문서입니다. 스키마는 클래스 정의에 내포되어 있으며, XmlSerializer.CanSerialize가 유효성을 검사하는 데 사용됩니다. xsd.exe 유틸리티를 사용하여 클래스에서 암시 적 스키마를 가져올 수 있습니다. –

+0

직렬화를 제어하는 ​​xml 특성이 모든 XSD 구문을 다루는 것은 아닙니다. 불행히도, 나는'XmlAttributeAttribute' 클래스에서 필수로 표시되는 xml 속성에 대한 옵션을 찾을 수 없습니다. 따라서 스키마 공급자를 사용하지 않으면 먼저 외부 XSD를 사용하고 XML을 유효하게하는 것이 필요합니다. –

관련 문제