Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Verify using C# if a XML file is broken

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.

like image 787
Shamim Hafiz - MSFT Avatar asked Jun 02 '11 13:06

Shamim Hafiz - MSFT


People also ask

What is program verification C?

Program verification is the process of applying formal methods directly to verification of code, rather than to a high-level specification.

Can I run C programming from mobile?

Android is based on Linux Kernel so it's definitely possible to compile & run C/C++ programs on Android. C is quite cross-platform , so a C Program written in Windows can Run on Linux ( and android ) and vice versa.


2 Answers

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.

like image 101
SLaks Avatar answered Sep 22 '22 20:09

SLaks


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.

like image 30
Alex Netkachov Avatar answered Sep 25 '22 20:09

Alex Netkachov