.Net里用XSD作XML合法性验证的代码片段

本文介绍了一个使用XML与XSD进行数据验证的具体案例,包括了Books.xml文件的内容及books.xsd样式文件的定义,并提供了C#代码实现对XML文件进行XSD验证的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现有Books.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<!-- edited with XMLSpy v2006 sp2 U (http://www.altova.com) by 10030452 (Kodak) -->
<books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="./books.xsd">
  <book>
    <name>hi</name>
    <isbn>1121</isbn>
  </book>
  <book>
    <name>hello</name>
    <isbn>1122</isbn>
  </book>
  <book>
    <name>world</name>
    <isbn>2211</isbn>
  </book>
  <book>
    <name>world1</name>
    <isbn>2212</isbn>
  </book>
</books>

 

和books.xsd的样式文件

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- edited with XMLSpy v2006 sp2 U (http://www.altova.com) by 10030452 (Kodak) -->
<!--W3C Schema generated by XMLSpy v2006 sp2 U (http://www.altova.com)-->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
 <xs:element name="book">
  <xs:complexType>
   <xs:sequence>
    <xs:element ref="name"/>
    <xs:element ref="isbn"/>
   </xs:sequence>
  </xs:complexType>
 </xs:element>
 
 <xs:element name="books">
  <xs:complexType>
   <xs:sequence>
    <xs:element ref="book" maxOccurs="unbounded"/>
   </xs:sequence>
  </xs:complexType>
  <xs:unique name="unique_bookname">
   <xs:selector xpath="book"/>
   <xs:field xpath="name"/>
  </xs:unique>
 </xs:element>
 <xs:element name="isbn">
  <xs:simpleType>
   <xs:restriction base="xs:short"/>
  </xs:simpleType>
 </xs:element>
 <xs:element name="name">
  <xs:simpleType>
   <xs:restriction base="xs:string"/>
  </xs:simpleType>
 </xs:element>
</xs:schema>

 

对其进行样式校验的Code如下:

 private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                using (XmlTextReader txtreader = new XmlTextReader("../../books.xml"))
                {
                    using (XmlValidatingReader oreader = new XmlValidatingReader(txtreader))
                    {
                            oreader.Schemas.Add(null, "../../books.xsd");
                        while (oreader.Read())
                        {
                        }
                    }
                }


                MessageBox.Show("Validation successfully");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }
   
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值