【问题标题】:XSD and XML ValidatorXSD 和 XML 验证器
【发布时间】:2012-05-22 07:14:05
【问题描述】:

我构建了一个应用程序来针对 XSd 验证 xml 文件。如果在一个节点中发生错误,它会引发异常,在该异常中我只能获得行号和行位置。如何获取该节点的最大长度值。

            MemoryStream xml = new MemoryStream();
            string xsd;
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            settings.Schemas.Add("", Application.StartupPath + "\\std_imaging.xsd");
            settings.ValidationEventHandler += MyValidationEventHandler;

            var v = XmlReader.Create(filename, settings);

            while (v.Read())
            {
                string a1 = v.ValueType.Name.Length.ToString();
                string name = v.NodeType + v.Name + v.ValueType + v.Value.ToString();
            }

       public void MyValidationEventHandler(object sender, ValidationEventArgs args)
       {
             schemaResult = false;
             textBox1.Text = textBox1.Text + (Environment.NewLine + args.Message +     
             Environment.NewLine +      "Location(" + args.Exception.LineNumber + 
             "," + args.Exception.LinePosition + ")" + Environment.NewLine);
       }

    this is my code.

【问题讨论】:

    标签: .net xml vb.net xsd validation


    【解决方案1】:

    我不久前遇到了同样的问题,并了解到获取特定节点的架构信息并不像人们想象的那么容易。我鼓励您了解为什么需要这些信息,以及是否值得花时间,因为这不是一个简单的解决方案。

    如果您对此以及将来有重大需求,最好的解决方案是直接使用IXmlSchemaInfo 对象模型,这样您就可以读取任何您想要的架构信息。在接受的答案中查看以下问题和blog post

    In C#, how to determine the XSD-defined MaxLength for an element

    它向您展示了有关IXmlSchemaInfo 对象模型的大量信息。它基本上涉及大量的类型检查和强制转换。由于您使用的是XmlReader,因此SchemaInfo 应该是阅读器的一部分,因此您可以获取当前节点的架构信息。

    该博客向您展示了如何读取任何节点的架构信息,实际上并没有将其绑定到验证中,但您可以轻松地将其调整为在您的验证回调方法中工作。

    public void MyValidationEventHandler(object sender, ValidationEventArgs args)
    {
        // Using `getMaxLength` method from blog code will return a list of max 
        //  lengths.  If there is more than one, you need to decide how to handle it.
        //  It would also be a good idea to add some addition null checking
        List<int> maxLengths = getMaxLength(sender as XmlReader);
    
        schemaResult = false;
        textBox1.Text = textBox1.Text + (Environment.NewLine + args.Message +     
            Environment.NewLine + "Location(" + args.Exception.LineNumber + 
            "," + args.Exception.LinePosition + ")" + Environment.NewLine);
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多