[代码]使用XSD验证XML示例(LINQ to XML)(转)
此代码演示如何使用LINQ to XML的XDocument.Validate()方法根据指定的XSD验证XDocument内容的有效性。
示例代码
using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Schema; using System.Xml.Linq; namespace Demo06Ex02 { class Program { static void Main(string[] args) { // ************************************************* // 这里对没有修改过的XML文档进行验证,能够通过。 // ************************************************* XmlSchemaSet Schemas = new XmlSchemaSet(); Schemas.Add("", @"C:/LINQ/CustomersOrders.xsd"); Console.WriteLine("Attempting to validate..."); XDocument Document = XDocument.Load(@"C:/LINQ/CustomersOrders.xml"); bool Errors = false; Document.Validate(Schemas, (o, e) => { Console.WriteLine(e.Message); Errors = true; }); Console.WriteLine("CustomersOrders.xml {0}", Errors ? "did not validate" : "validated"); Console.WriteLine(); // ******************************************************** // 修改了客户的编号之后,再次验证就引发了异常。 // ******************************************************** Document.Root.Element("Orders").Element("Order") .Element("CustomerID").Value = "AAAAA"; Console.WriteLine("Attempting to validate after modification..."); Errors = false; Document.Validate(Schemas, (o, e) => { Console.WriteLine(e.Message); Errors = true; }); Console.WriteLine("CustomersOrders.xml {0}", Errors ? "did not validate" : "validated"); } } }
原文地址: http://blog.csdn.net/gjysk/article/details/5972972

浙公网安备 33010602011771号