What is the easiest/simplest/cleanest way to:
Using .net.
XML documents are validated by the Create method of the XmlReader class. To validate an XML document, construct an XmlReaderSettings object that contains an XML schema definition language (XSD) schema with which to validate the XML document.
Notepad++ in combination with the XML Tools Plugin and the XidML schema is a smart way to validate XidML files (basically any XML file where you have a schema).
For obtaining an XML response, we have to pass the parameter ContentType. XML to the accept method. We shall first send a GET request via Postman on a mock API URL. Using Rest Assured, we shall validate its XML Response containing the name of the subjects Rest Assured, Postman, and their prices 10 and 6 respectively.
Basically, to get a XSD validation going, you'll need to use a XmlReader with ReaderSettings that define what XSD file to validate against, and events to respond / catch validation errors.
To read the XSD file, use something like this:
StreamReader xsdReader = new StreamReader(xsdFileName);
XmlSchema Schema = new XmlSchema();
Schema = XmlSchema.Read(xsdReader, new ValidationEventHandler(XSDValidationEventHandler));
and the event handler to catch any errors that might show up while reading the XSD (e.g. if it in itself is invalid) would have this signature:
private static void XSDValidationEventHandler(object sender, ValidationEventArgs e)
The error message is in e.Message.
Once you have the XSD loaded in memory, instantiate your XmlReader and use the proper settings to enforce XSD validation:
XmlReaderSettings ReaderSettings = new XmlReaderSettings();
ReaderSettings.ValidationType = ValidationType.Schema;
ReaderSettings.Schemas.Add(Schema);
ReaderSettings.ValidationEventHandler += new ValidationEventHandler(XMLValidationEventHandler);
This error event handler has the same signature as the one above.
Then actually read the file from beginning to end:
XmlTextReader xmlReader = new XmlTextReader(xmlFileName);
XmlReader objXmlReader = XmlReader.Create(xmlReader, ReaderSettings);
while (objXmlReader.Read()) { }
If any validation errors occured, your event handler was called, and you can capture the error messages in there and e.g. display them to the user (or just have a flag indicating whether validation was successful or not - your call :) )
Depending on the level of tolerance and error reporting you want to have, you might find the new XML Api introduced in .NET 3.5 to be useful - the classes XDocument, XElement, XAttribute and so on, all from the System.Xml.Linq namespace.
The design of new XML Api was heavily influenced by lessons learned from the older XMLDocument design, and is much more lightweight and easier to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With