Reputation: 22114
Is there anything built in to determine if an XML file is valid. One way would be to read the entire content and verify if the string represents valid XML content. Even then, how to determine if string contains valid XML data.
Upvotes: 5
Views: 3968
Reputation: 13562
You can try to load the XML into XML document and catch the exception. Here is the 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 it helps.
Upvotes: 4
Reputation: 888177
Create an XmlReader
around a StringReader with the XML and read through the reader:
using (var reader = XmlReader.Create(something))
while(reader.Read())
;
If you don't get any exceptions, the XML is well-formed.
Unlike XDocument or XmlDocument, this will not hold an entire DOM tree in memory, so it will run quickly even on extremely large XML files.
Upvotes: 12
Reputation: 41579
Have a look at this question:
How to check for valid xml in string input before calling .LoadXml()
Upvotes: 0