Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one test a file to see if it's a valid XML file before loading it with XDocument.Load()?

I'm loading an XML document in my C# application with the following:

XDocument xd1 = new XDocument();
xd1 = XDocument.Load(myfile);

but before that, I do test to make sure the file exists with:

File.Exists(myfile);

But... is there an (easy) way to test the file before the XDocument.Load() to make sure it's a valid XML file? In other words, my user can accidentally click on a different file in the file browser and trying to load, say, a .php file causes an exception.

The only way I can think of is to load it into a StreamWriter and simple do a text search on the first few characters to make sure they say "

Thanks!

-Adeena

like image 909
adeena Avatar asked Dec 17 '08 18:12

adeena


People also ask

How can you check an XML document is both valid and well-formed document?

To check whether an XML document is well-formed or not, you have to use an XML parser. An XML parser is a Software Application, which introspects an XML document and stores the resulting output in memory.

How do I load an XML document and validate it?

To validate the XML in the DOM, you can validate the XML as it is loaded into the DOM by passing a schema-validating XmlReader to the Load method of the XmlDocument class, or validate a previously unvalidated XML document in the DOM using the Validate method of the XmlDocument class.

Which tool is used to check whether XML document is valid or not?

Tools. xmllint is a command line XML tool that can perform XML validation. It can be found in UNIX / Linux environments. XML Validator Online Validate your XML data.


2 Answers

It's probably just worth catching the specific exception if you want to show a message to the user:

 try
 {
   XDocument xd1 = new XDocument();
   xd1 = XDocument.Load(myfile);
 }
 catch (XmlException exception)
 {
     ShowMessage("Your XML was probably bad...");
 }
like image 106
Jennifer Avatar answered Oct 25 '22 16:10

Jennifer


This question confuses "well-formed" with "valid" XML document.

A valid xml document is by definition a well formed document. Additionally, it must satisfy a DTD or a schema (an xml schema, a relaxng schema, schematron or other constraints) to be valid.

Judging from the wording of the question, most probably it asks:

"How to make sure a file contains a well-formed XML document?".

The answer is that an XML document is well-formed if it can be parsed successfully by a compliant XML parser. As the XDocument.Load() method does exactly this, you only need to catch the exception and then conclude that the text contained in the file is not well formed.

like image 26
Dimitre Novatchev Avatar answered Oct 25 '22 17:10

Dimitre Novatchev