2012-12-21 43 views
1

這個代碼不驗證XML正確能否請您發現錯誤一個Xml ....即使我與無效的XML執行它不產生任何錯誤如何驗證使用XSD

using System.Xml; 

namespace XmlTryProject 
{ 
    internal class Program 
    { 
     private static void Main(string[] args) 
     { 
      XmlReaderSettings readSettings = new XmlReaderSettings(); 
      readSettings.ValidationType = ValidationType.Schema; 
      readSettings.Schemas.Add(null, 
    @"C:\Visual Studio 2010\Projects\XmlTry \XmlTryProject\EmployeeXSD.xsd"); 

      readSettings.ValidationEventHandler += 
       new System.Xml.Schema.ValidationEventHandler(Validater); 

      XmlReader xReader = XmlReader.Create(
    @"C:\Visual Studio 2010\Projects\XmlTry\XmlTryProject\EmployeeXML.xml", 
       readSettings); 

      while (xReader.Read()) 
      { 
       if (xReader.NodeType == XmlNodeType.Element) 
       { 
        Console.WriteLine(xReader.Name); 
       } 
      } 
     } 

     public static void Validater(object sender, 
          System.Xml.Schema.ValidationEventArgs args) 
     { 
      Console.WriteLine(args.Message); 
     } 
    } 
} 
+0

我懷疑計算器問題將有所幫助:http://stackoverflow.com/questions/751511/validating-an-xml-against-referenced-xsd-in-c-sharp –

回答

2

它看起來你忘了ValidationFlags

readSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema; 
readSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation; 
readSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings; 
0

下面是使用LINQ to XML的簡單方法。
ValidateXmlFile方法是如何使用它的一個示例。

private static void ValidateXmlFile() 
{ 
    using (var xmlFile = File.OpenRead("networkshares.xml")) 
    using (var xmlSchemaFile = File.OpenRead("networkshares.xsd")) 
    { 
     ValidateXml("netuseperdomain.networkshares", xmlSchemaFile, xmlFile); 
    } 
} 

public static void ValidateXml(string targetNamespace, Stream xmlSchema, Stream xml) 
{ 
    var xdoc = XDocument.Load(xml); 
    var schemas = new XmlSchemaSet(); 
    schemas.Add(targetNamespace, new XmlTextReader(xmlSchema)); 

    xdoc.Validate(schemas, (sender, e) => 
    { 
     throw new Exception(e.Message); 
    }); 
}