How to check C # usage if XML file is corrupted

Is there anything built-in to determine if the XML file is valid. One way is to read all the content and check if the string matches the actual XML content. Even then, how to determine if a string contains valid XML data.

+5
source share
3 answers

You can try loading XML into an XML document and catch the exception. Here is a sample code:

var doc = new XmlDocument();
try {
  doc.LoadXml(content);
} catch (XmlException e) {
  // put code here that should be executed when the XML is not valid.
}

Hope this helps.

+4
source

Create XmlReaderaround StringReader with XML and read through the reader:

using (var reader = XmlReader.Create(something))
    while(reader.Read()) 
        ;

If you don't get any exceptions, XML is well formed.

XDocument XmlDocument, DOM , XML.

+11

All Articles