XML validation with XSD file

Viewed 237

I try to validate my xml structure, using an xml schema.

This code sample is given here : https://docs.microsoft.com/en-us/dotnet/api/system.xml.xmldocument.validate?view=net-5.0

 XmlReaderSettings settings = new XmlReaderSettings();
        settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd");
        settings.ValidationType = ValidationType.Schema;

        XmlReader reader = XmlReader.Create("contosoBooks.xml", settings);
        XmlDocument document = new XmlDocument();
        document.Load(reader);

        ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);

        // the following call to Validate succeeds.
        document.Validate(eventHandler);

        // add a node so that the document is no longer valid
        XPathNavigator navigator = document.CreateNavigator();
        navigator.MoveToFollowing("price", "http://www.contoso.com/books");
        XmlWriter writer = navigator.InsertAfter();
        writer.WriteStartElement("anotherNode", "http://www.contoso.com/books");
        writer.WriteEndElement();
        writer.Close();

        // the document will now fail to successfully validate
        document.Validate(eventHandler);

Problem is that when I'm using a non valide xml document, I already have an exception of type System.Xml.Schema.XmlSchemaValidationException on line :

XmlReader reader = XmlReader.Create("contosoBooks.xml", settings);

Does this mean you dont need to use this Validate(eventHandler) method with C# 6 anymore ? Or will it take care of few specific validation problems ?

0 Answers
Related