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.
Asked
Active
Viewed 3,830 times
3 Answers
12
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.

SLaks
- 868,454
- 176
- 1,908
- 1,964
4
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.

Alex Netkachov
- 13,172
- 6
- 53
- 85
-
1It should be noted that if you try something like this on a very large yet perfectly valid xml string, you may throw an OutOfMemoryException. – Mark Bailey Feb 16 '17 at 17:44
0
Have a look at this question:
How to check for valid xml in string input before calling .LoadXml()

Community
- 1
- 1

Jon Egerton
- 40,401
- 11
- 97
- 129