2013-10-02 131 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的唯一標準是 「有效」 的是,它完全形成了。