Andy
Andy

Reputation: 2318

How to validate an XML with an XSD using LINQ

EDIT2: the problem seems to be my xsd. it validates pretty much every XML. i can't post the XSD on here though. why would every XML be valid for an XSD?

EDIT: found a similar excample in the answer on here. Same issue, it finds no errors no matter what xml and xsd i compare. even if i use a random diffrent xsd it keeps saying it is all fine.

I found a lot of examples doing it without LINQ, but how would you do it with LINQ?

I used Google to find an example but it seems to skip the validation most of the time validating every XML. (it once went into it, rejecting the file but I haven't been able to reproduce it.)

Are there better ways of doing it or is there a reason why it would skip over the validation?

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

Upvotes: 0

Views: 3645

Answers (1)

Jason Ridge
Jason Ridge

Reputation: 1868

Apparently using LINQ to XML you have to have the schemas targetNamespace match the namespace of the xml you are checking, because the validate method looks through the collection of schemas for one validating that documents namespace. If one is not found then the document is validated.

check out this link for more info

Upvotes: 1

Related Questions