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
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.
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.
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.
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...");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With