2009-08-14 54 views

回答

15

試試這個:

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

這是我用過的最快的一個。 – 2011-12-22 13:53:41

2

希望這有助於鏈接:

Validation of XML with XSD

+1

鏈接看起來不錯,但我注意到的例子是使用一個XmlValidatingReader,這是過時的。查看股票XmlReader和XmlReaderSettings,其中包含一些驗證屬性以定義行爲。 – STW 2009-08-14 12:42:04

5

我得到CODE呢!我在我的測試中使用這樣的:在模式

public static bool IsValid(XElement element, params string[] schemas) 
    { 
     XmlSchemaSet xsd = new XmlSchemaSet(); 
     XmlReader xr = null; 
     foreach (string s in schemas) 
     { // eh, leak 'em. 
      xr = XmlReader.Create(
       new MemoryStream(Encoding.Default.GetBytes(s))); 
      xsd.Add(null, xr); 
     } 
     XDocument doc = new XDocument(element); 
     var errored = false; 
     doc.Validate(xsd, (o, e) => errored = true); 
     if (errored) 
      return false; 

     // If this doesn't fail, there's an issue with the XSD. 
     XNamespace xn = XNamespace.Get(
         element.GetDefaultNamespace().NamespaceName); 
     XElement fail = new XElement(xn + "omgwtflolj/k"); 
     fail.SetAttributeValue("xmlns", xn.NamespaceName); 
     doc = new XDocument(fail); 
     var fired = false; 
     doc.Validate(xsd, (o, e) => fired = true); 
     return fired; 
    } 

這其中需要作爲字符串(文件資源組件中的),並將它們添加到架構集。我驗證,如果它無效,我會返回false。

如果xml沒有被發現是無效的,我做一個否定檢查,以確保我的模式沒有搞砸。它不保證萬無一失,但我用這個來發現我的模式中的錯誤。

+1

您可能想嘗試使用'XmlSchema.Read'方法,因爲它可以在解析模式時驗證模式。 – 2009-08-14 13:25:33

+0

感謝您的代碼:) – BigOmar 2012-05-01 16:23:04

3

簡單的解決方案..

 try 
     { 
      XmlReaderSettings Xsettings = new XmlReaderSettings(); 
      Xsettings.Schemas.Add(null, "personDivideSchema.xsd"); 
      Xsettings.ValidationType = ValidationType.Schema; 

      XmlDocument document = new XmlDocument(); 
      document.Load("person.xml"); 

      XmlReader reader = XmlReader.Create(new StringReader(document.InnerXml), Xsettings); 


      while (reader.Read()); 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e.Message.ToString()); 
     }