[代码]使用XSD验证XML示例1(LINQ to XML)

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"); } } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值