【问题标题】:How to validate an XML with an XSD using LINQ如何使用 LINQ 使用 XSD 验证 XML
【发布时间】:2011-07-22 08:27:19
【问题描述】:

EDIT2:问题似乎出在我的 xsd 上。它几乎验证了每一个 XML。我不能在这里发布 XSD。为什么每个 XML 都对 XSD 有效?

编辑:在here 的答案中找到了类似的示例。同样的问题,无论我比较什么 xml 和 xsd,它都没有发现错误。即使我使用随机不同的 xsd,它也会一直说一切都很好。

我发现了很多不使用 LINQ 的例子,但是你会如何使用 LINQ 呢?

我使用 Google 查找了一个示例,但它似乎在大多数情况下都跳过了验证每个 XML 的验证。 (它曾经进入它,拒绝该文件,但我无法重现它。)

有没有更好的方法,或者它是否有理由跳过验证?

public String ValidateXml2(String xml, String xsd)
    {
        String Message = String.Empty;

        var ms = new MemoryStream(Encoding.Default.GetBytes(xml));

        // Create the XML document to validate against.
        XDocument xDoc = XDocument.Load(ms, LoadOptions.PreserveWhitespace);
        XmlSchemaSet schema = new XmlSchemaSet();

        bool isError = new bool();  // Defaults to false.
        int countError = 1;         // Counts the number of errors have generated.
        Stream xsdMemoryStream = new MemoryStream(Encoding.Default.GetBytes(xsd));

        // Add the schema file you want to validate against.
        schema.Add(XmlSchema.Read
                (xsdMemoryStream,
                    new ValidationEventHandler((sender, args) =>
                    {
                        Message = args.Exception.Message;
                    })
                ));

        // Call validate and use a LAMBDA Expression as extended method!
        // Don't you love .NET 3.5 and LINQ...
        xDoc.Validate(schema, (sender, e) =>
        {
            switch (e.Severity)
            {
                case XmlSeverityType.Error:
                    Console.WriteLine("Error {0} generated.", countError);
                    break;
                case XmlSeverityType.Warning:
                    Console.WriteLine("Warning {0} generated.", countError);
                    break;
            }
            Console.WriteLine(sender.GetType().Name);
            Console.WriteLine("\r\n{0}\r\nType {1}\r\n", e.Message,
                                                         e.Severity.ToString());

            Console.WriteLine("-".PadRight(110, '-'));
            countError++;
            isError = true; // If error fires, flag it to handle once call is complete.
        }
          , true); // True tells the validate call to populate the post-schema-validation
        // which you will need later, if you want to dive a littel deeper...

        if (isError == true) // Error has been flagged.  Lets see the errors generated.
            Console.WriteLine("You my friend have {0} error(s), now what?", countError);
        else
            Console.WriteLine("You rock! No errors...");

        Console.Write("\r\n\r\nPress Enter to End");
        Console.ReadKey();


        return Message;
    }

Credits and original example

【问题讨论】:

    标签: xml linq c#-4.0 xsd


    【解决方案1】:

    显然,使用 LINQ to XML,您必须让架构 targetNamespace 与您正在检查的 xml 的命名空间相匹配,因为 validate 方法会在架构集合中查找一个验证该文档命名空间的架构。如果未找到,则验证该文档。

    查看this link for more info

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-23
      相关资源
      最近更新 更多