在C#中用xsd文件验证xml文件的格式正确性

person.xml:(不带命名空间)

<?xml version="1.0" encoding="UTF-8"?>
<Persons>
  <Person id="1">
    <Name>张三</Name>
    <Age>120</Age>
  </Person>
  <Person id="2">
    <Name>李四</Name>
    <Age>20</Age>
  </Person>
</Persons>

person.xsd:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">

  <xs:annotation>
    <xs:documentation> 本文档定义Persons.xml的格式 </xs:documentation>
  </xs:annotation>
  <xs:element name="Persons">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Person" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Name">
                <xs:simpleType>
                  <xs:restriction base="xs:string">
                    <xs:minLength value="2" />
                    <xs:maxLength value="4" />
                  </xs:restriction>
                </xs:simpleType>
              </xs:element>
              <xs:element name="Age">
                <xs:simpleType>
                  <xs:restriction base="xs:string">
                    <xs:pattern value="[1-9][0-9]?|1[01][0-9]|120" />
                  </xs:restriction>
                </xs:simpleType>
              </xs:element>
            </xs:sequence>
            <xs:attribute name="id" use="required">
              <xs:simpleType>
                <xs:restriction base="xs:int"></xs:restriction>
              </xs:simpleType>
            </xs:attribute>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>

验证方法:

        /// <summary>  
        /// 通过xsd验证xml格式是否正确,正确返回空字符串,错误返回提示  
        /// </summary>  
        /// <param name="xmlFile">xml文件</param>  
        /// <param name="xsdFile">xsd文件</param>  
        /// <param name="namespaceUrl">命名空间,无则默认为null</param>  
        /// <returns></returns>  
        public static string XmlValidationByXsd(string xmlFile, string xsdFile, string namespaceUrl = null)
        {
            StringBuilder sb = new StringBuilder();
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            settings.Schemas.Add(namespaceUrl, xsdFile);
            //验证出错时执行
            settings.ValidationEventHandler += (x, y) =>
            {
                sb.AppendFormat("{0}|", y.Message);
            };
            using (XmlReader reader = XmlReader.Create(xmlFile, settings))
            {
                try
                {
                    while (reader.Read()) ;
                }
                catch (XmlException ex)
                {
                    sb.AppendFormat("{0}|",ex.Message);
                }
            }
            return sb.ToString();
        }
上面代码是验证xml文件,如果是xml字符串,则可用下面:

           /// <summary>  
           /// 通过xsd验证xml格式是否正确,正确返回空字符串,错误返回提示  
           /// </summary>  
           /// <param name="xmlText">xml文本内容</param>  
           /// <param name="schemaFile">xsd文件</param>  
           /// <returns></returns>  
           public static string XmlValidateByXsd(string xmlText, string schemaFile)  
           {  
               StringBuilder sb = new StringBuilder();  
               XmlReaderSettings settings = new XmlReaderSettings();  
               settings.ValidationType = ValidationType.Schema;  
               settings.Schemas.Add(null, schemaFile);  
               settings.ValidationEventHandler += (x, y) =>  
               {  
                   sb.AppendFormat("{0}\n", y.Message);  
               };  
               using (XmlReader reader = XmlReader.Create(new StringReader(xmlText), settings))  
               {  
                   try  
                   {  
                       while (reader.Read()) ;  
                   }  
                   catch (XmlException ex)  
                   {  
                       sb.AppendFormat("{0}\n", ex.Message);  
                   }  
               }  
               return sb.ToString();  
           }  


https://msdn.microsoft.com/en-us/library/system.xml.xmldocument(v=vs.110).aspx

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值