【问题标题】:Possible to validate xml against xsd using code at runtime?可以在运行时使用代码针对 xsd 验证 xml 吗?
【发布时间】:2010-11-19 15:22:22
【问题描述】:

我有在运行时读取的 xml 文件,是否可以在运行时针对 xsd 文件验证 xml?使用c#

【问题讨论】:

    标签: c# xml xsd schema xml-validation


    【解决方案1】:

    更简单的解决方案..

            try
            {
                XmlReaderSettings Xsettings = new XmlReaderSettings();
                Xsettings.Schemas.Add(null, "personDivideSchema.xsd");
                Xsettings.ValidationType = ValidationType.Schema;
    
                XmlDocument document = new XmlDocument();
                document.Load("person.xml");
    
                XmlReader reader = XmlReader.Create(new StringReader(document.InnerXml), Xsettings);
    
    
                while (reader.Read());
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message.ToString());
            }
    

    【讨论】:

      【解决方案2】:

      我也有代码!我在测试中使用它:

          public static bool IsValid(XElement element, params string[] schemas)
          {
              XmlSchemaSet xsd = new XmlSchemaSet();
              XmlReader xr = null;
              foreach (string s in schemas)
              { // eh, leak 'em. 
                  xr = XmlReader.Create(
                      new MemoryStream(Encoding.Default.GetBytes(s)));
                  xsd.Add(null, xr);
              }
              XDocument doc = new XDocument(element);
              var errored = false;
              doc.Validate(xsd, (o, e) => errored = true);
              if (errored)
                  return false;
      
              // If this doesn't fail, there's an issue with the XSD.
              XNamespace xn = XNamespace.Get(
                            element.GetDefaultNamespace().NamespaceName);
              XElement fail = new XElement(xn + "omgwtflolj/k");
              fail.SetAttributeValue("xmlns", xn.NamespaceName);
              doc = new XDocument(fail);
              var fired = false;
              doc.Validate(xsd, (o, e) => fired = true);
              return fired;
          }
      

      这个将模式作为字符串(程序集中的文件资源)接收,并将它们添加到模式集中。我验证,如果它无效,我返回 false。

      如果没有发现 xml 无效,我会进行否定检查以确保我的架构没有搞砸。它不能保证万无一失,但我用它来查找我的架构中的错误。

      【讨论】:

      • 您可能想尝试使用XmlSchema.Read 方法,因为它可以在解析模式时验证模式。
      【解决方案3】:

      试试这个:

      public void ValidateXmlDocument(
          XmlReader documentToValidate, string schemaPath)
      {
          XmlSchema schema;
          using (var schemaReader = XmlReader.Create(schemaPath))
          {
              schema = XmlSchema.Read(schemaReader, ValidationEventHandler);
          }
      
          var schemas = new XmlSchemaSet();
          schemas.Add(schema);
      
          var settings = new XmlReaderSettings();
          settings.ValidationType = ValidationType.Schema;
          settings.Schemas = schemas;
          settings.ValidationFlags =
              XmlSchemaValidationFlags.ProcessIdentityConstraints |
              XmlSchemaValidationFlags.ReportValidationWarnings;
          settings.ValidationEventHandler += ValidationEventHandler;
      
          using (var validationReader = XmlReader.Create(documentToValidate, settings))
          {
              while (validationReader.Read())
              {
              }
          }
      }
      
      private static void ValidationEventHandler(
          object sender, ValidationEventArgs args)
      {
          if (args.Severity == XmlSeverityType.Error)
          {
              throw args.Exception;
          }
      
          Debug.WriteLine(args.Message);
      }
      

      【讨论】:

      • 这是最快的,我用过。
      猜你喜欢
      • 2012-02-14
      • 1970-01-01
      • 2012-09-26
      • 2011-07-18
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多