如何使用LINQ使用XSD验证XML

时间:2011-07-22 08:27:20

标签: xml linq c#-4.0 xsd

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

1 个答案:

答案 0 :(得分:1)

显然使用LINQ to XML,您必须让模式targetNamespace与您正在检查的xml的名称空间匹配,因为validate方法会查看一个模式集合,以验证文档名称空间。如果找不到,则验证文件。

结帐this link for more info