LINQ to XML的XDocument.Validate()方法是用来验证XML文档是否有效的,此方法需要指定验证所需的XSD,而这可以通过XmlSchemaSet对象提供,XmlSchemaSet.Add()方法可以将指定的XSD加载到验证集中。这样就可以使用此XSD来验证XML内容的有效性了。
示例代码
此示例代码验证了两个XDocument对象的有效性。Document1是有效的,而Document2是无效的。因为Document2中包含了一个名为Child3的元素,而这在XSD架构中并没有定义,因此导致了验证的异常。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Schema; using System.Xml; using System.IO; using System.Xml.Linq; namespace Demo06Ex01 { class Program { static void Main(string[] args) { string XsdMarkup = @"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <xsd:element name='Root'> <xsd:complexType> <xsd:sequence> <xsd:element name='Child1' minOccurs='1' maxOccurs='1'/> <xsd:element name='Child2' minOccurs='1' maxOccurs='1'/> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema>"; XmlSchemaSet Schemas = new XmlSchemaSet(); Schemas.Add("", XmlReader.Create(new StringReader(XsdMarkup))); XDocument Document1 = new XDocument( new XElement("Root", new XElement("Child1", "Content1"), new XElement("Child2", "Content1"))); XDocument Document2 = new XDocument( new XElement("Root", new XElement("Child1", "Content1"), new XElement("Child3", "Content1"))); Console.WriteLine("Validating Document1..."); bool Errors = false; Document1.Validate(Schemas, (o, e) => { Console.WriteLine("{0}", e.Message); Errors = true; }); Console.WriteLine("Document1 {0}", Errors ? "did not validate" : "validated"); Console.WriteLine(); Console.WriteLine("Validating Document2..."); Errors = false; Document2.Validate(Schemas, (o, e) => { Console.WriteLine(e.Message); Errors = true; }); Console.WriteLine("Document2 {0}", Errors ? "did not validate" : "validated"); } } }