2013-10-02 132 views
0

我正在写需要XML文件进行验证WPF应用程序验证XML对XSD。我有以下类验证XML针对一种或多种XSD文件:需要帮助的C#

public class XSDValidator 
{ 
    public List<XmlSchema> Schemas { get; set; } 
    public List<String> Errors { get; set; } 
    public List<String> Warnings { get; set; } 

    public XSDValidator() 
    { 
     Schemas = new List<XmlSchema>(); 
    } 

    /// <summary> 
    /// Add a schema to be used during the validation of the XML document 
    /// </summary> 
    /// <param name="schemaFileLocation">The file path for the XSD schema file to be added for validation</param> 
    /// <returns>True if the schema file was successfully loaded, else false (if false, view Errors/Warnings for reason why)</returns> 
    public bool AddSchema(string schemaFileLocation) 
    { 
     // Reset the Error/Warning collections 
     Errors = new List<string>(); 
     Warnings = new List<string>(); 

     XmlSchema schema; 

     if (!File.Exists(schemaFileLocation)) 
     { 
      throw new FileNotFoundException("The specified XML file does not exist", schemaFileLocation); 
     } 

     using (var fs = new FileStream(schemaFileLocation, FileMode.Open)) 
     { 
      schema = XmlSchema.Read(fs, ValidationEventHandler); 
     } 

     var isValid = !Errors.Any() && !Warnings.Any(); 

     if (isValid) 
     { 
      Schemas.Add(schema); 
     } 

     return isValid; 
    } 

    /// <summary> 
    /// Perform the XSD validation against the specified XML document 
    /// </summary> 
    /// <param name="xmlLocation">The full file path of the file to be validated</param> 
    /// <returns>True if the XML file conforms to the schemas, else false</returns> 
    public bool IsValid(string xmlLocation) 
    { 
     if (!File.Exists(xmlLocation)) 
     { 
      throw new FileNotFoundException("The specified XML file does not exist", xmlLocation); 
     } 

     using (var xmlStream = new FileStream(xmlLocation, FileMode.Open)) 
     { 
      return IsValid(xmlStream); 
     } 
    } 

    /// <summary> 
    /// Perform the XSD validation against the supplied XML stream 
    /// </summary> 
    /// <param name="xmlStream">The XML stream to be validated</param> 
    /// <returns>True is the XML stream conforms to the schemas, else false</returns> 
    private bool IsValid(Stream xmlStream) 
    { 
     // Reset the Error/Warning collections 
     Errors = new List<string>(); 
     Warnings = new List<string>(); 

     var settings = new XmlReaderSettings 
     { 
      ValidationType = ValidationType.Schema 
     }; 
     settings.ValidationEventHandler += ValidationEventHandler; 

     foreach (var xmlSchema in Schemas) 
     { 
      settings.Schemas.Add(xmlSchema); 
     } 

     var xmlFile = XmlReader.Create(xmlStream, settings); 

     while (xmlFile.Read()) { } 

     return !Errors.Any() && !Warnings.Any(); 
    } 

    private void ValidationEventHandler(object sender, ValidationEventArgs e) 
    { 
     switch (e.Severity) 
     { 
      case XmlSeverityType.Error: 
       Errors.Add(e.Message); 
       break; 
      case XmlSeverityType.Warning: 
       Warnings.Add(e.Message); 
       break; 
     } 
    } 
} 

上面的代码是开源和可以发现here。现在,它被称为像这样:

var validator = new XSDValidator(); 
validator.AddSchema(@"C:\code\xml\books.xsd"); 

foreach (CheckableListItem file in FileFullPathChecklist) 
{ 
    if (file.IsChecked) 
    { 
     if (validator.IsValid(file.Filename)) 
     { 
      ValidatedXMLFiles++; 
     } 
    } 
} 

在我的XSD验证测试,我使用4个XML文件:他们中的一个,books.xml,对应于硬编码模式books.xsd。其他三个是我从其他来源获取的随机XML文件,并且我已验证它们对books.xsd无效。然而,在运行代码,ValidatedXMLFiles显示,我可以从XSDValidator类想到的4而不是1

我已经验证了尽可能多的值;我尝试手动添加一个随机字符串到ErrorsIsValid在这种情况下返回false。我认为有趣的一件事是,当我尝试将架构文件名更改为不存在的东西时,引发TargetInvocationException而不是我期望的FileNotFoundException。我不知道这是否意味着什么,但这是我见过的唯一奇怪的行为。任何人都可以提供协助吗?

+0

嗨椰子琼斯,我会非常有兴趣研究这一点。是否有可能获得这些文件,以便我可以尝试将其复制到我的电脑上。我显然想确保我的代码正常工作。 – Satal

回答

0

你假设验证引擎将automotically知道使用books.xsd架构验证所有的XML文件。

这是不正确的。 xml需要告诉验证器它应该被验证的XSD。

为了说明这一点,你设置的xmlns XML文档中的属性。

例如:

<MyXml xmlns="http://MySchemaNamespace"> 
    ... 
</MyXml> 

和架构:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
      targetNamespace="http://MySchemaNamespace" 
      xmlns="http://MySchemaNamespace" 
      elementFormDefault="qualified"> 
    ... 
</xs:schema> 

否则对XML的唯一标准是 “有效” 的是,它完全形成了。