user1995725
user1995725

Reputation: 1

How do I validate an XML file in C#, I have an Instance of XMLDocument in my Code, I don't want to use XMLReader though?

I already have an XMLDocument object in my code and I want to validate that object. I have the XSD file with me. I found a way of validating it using the xmlreader but I am not using the Xml Reader anywhere in my code. I have an XMLDocument instance ready.

Upvotes: 0

Views: 350

Answers (2)

user1995725
user1995725

Reputation: 1

XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Schemas.Add("http://www.w3.org/2001/XMLSchema", "fileName.xsd"); ValidationEventHandler validationEventHandler = new System.Xml.Schema.ValidationEventHandler(ValidationEVentHandler); xmlDoc.Load("fileName.xml"); xmlDoc.Validate(validationEventHandler);

public void ValidationEventHandler(object sender, ValidationEventArgs e) { switch (e.Severity) { case XmlSeverityType.Error: lblLabel.Text= e.Message; break; case XmlSeverityType.Warning: lblLabel.Text = e.Message; break; } }

Upvotes: 0

energ1ser
energ1ser

Reputation: 2873

You can use the schemas property on your XmlDocument object to add the xsd like so.

xmlDoc.Schemas.Add(namespace, xsdFileName);

then you can load your xml file and then call the Validate method passing it a ValidationEventHandler like so.

xmlDoc.Load(xmlfileName);
xmlDoc.Validate(handler);

Upvotes: 3

Related Questions