如何对不同的xml文件属性进行Schematron验证

时间:2014-05-29 05:11:45

标签: c# xml xsd xml-validation schematron

我有一个source1.xml文件

<?xml version="1.0" encoding="utf-8" ?>
<list>
  <author id="a1">Alice</author>
  <author id="p1">Paul</author>
  <author id="p2">Peter</author>
</list>

另一个source2.xml

<?xml version="1.0" encoding="utf-8" ?>
<list>
  <author id="1"/>
  <author id="a2"/>
  <author id="p1"/>
</list>

我需要验证两个xml文件的“id”属性是否具有相同的值。 我可以使用这个链接(http://zvon.org/xxl/SchematronTutorial/Examples/Example17/example.html

中显示的schematron来完成

所以我在xsd文件(source2.xsd)上创建了我的schematron,如下所示

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="list">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="author">

          <xs:annotation>
            <xs:appinfo>
              <sch:pattern name ="Compare AdaptiveDisplayDevice Id with DisplayDevice Id" xmlns:sch="http://www.ascc.net/xml/schematron">

                <rule context="author">
                  <report test="document('source1.xml')//author[@id=current()/@id]">
                    Atrribute
                    <name path="document('source1.xml')//author[@id=current()/@id]"/> is forbidden in element
                    <name/>
                  </report>
                </rule>

              </sch:pattern>
            </xs:appinfo>
          </xs:annotation>

          <xs:complexType>
            <xs:attribute name="id" type="xs:string" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

我的C#验证代码如下所示

using System.Text;
using NMatrix.Schematron;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {

                /* setup schematron validation */
                Validator validator = new Validator();
                validator.AddSchema(@"D:\POC\ConsoleApplication1\ConsoleApplication1\source2.xsd");

                /* run both validators at once */
                validator.Validate(new XmlTextReader(@"D:\POC\ConsoleApplication1\ConsoleApplication1\source2.xml"));

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

        }
    } 
}

如果我们观察两个xml文件,那么在使用schematron进行验证时,它应该在前两个id值时给出错误。但是我没有收到任何错误.. 谁能在这帮助我......

0 个答案:

没有答案