需要帮助掌握Commons.Xml.Relaxng中的RelaxngValidatingReader

时间:2017-06-30 19:05:49

标签: xml relaxng relaxng-compact

环境:RelaxngValidatingReader .Net 2.0 Framework

无论我多少改变xml,我似乎无法使验证器等于假。我在这里错过了一些概念吗?

资源
https://github.com/mono/mono/tree/master/mcs/class/Commons.Xml.Relaxng

紧凑格式

start = root
root = element root { parent1* & parent2* }
parent1 = element parent1 { element field { attribute usecase_123 {text} } }
parent2 = element parent2 { element field { attribute usecase_AAA {text} } }

xml实例

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <parent1>
    <hello/>
  </parent1>
</root>

主程序

static void Main(string[] args)
{
    RncParser parser = new RncParser(new NameTable());
    TextReader source = new StreamReader("test.rnc");
    RelaxngPattern grammar = parser.Parse(source);

    XmlReader instance = new XmlTextReader("XMLFile1.xml");
    RelaxngValidatingReader reader = new RelaxngValidatingReader(instance, grammar);
    Console.WriteLine("Was the xml valid? {0}", reader.Read());
}

1 个答案:

答案 0 :(得分:0)

您必须重复Read()直到文档结束:

static void Main(string[] args)
{
    RncParser parser = new RncParser(new NameTable());
    TextReader source = new StreamReader("test.rnc");
    RelaxngPattern grammar = parser.Parse(source);

    XmlReader instance = new XmlTextReader("XMLFile1.xml");
    RelaxngValidatingReader reader = new RelaxngValidatingReader(instance, grammar);
    try {
        while (!reader.EOF) {
            reader.Read();
        }
        Console.WriteLine("validation succeeded");
    }
    catch (Exception ex) {
        Console.WriteLine("validation failed with message:");
        Console.WriteLine(ex.Message);
    }
}