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

后端 未结 7 1942
挽巷
挽巷 2020-12-28 14:24

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

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

but be

7条回答
  •  既然无缘
    2020-12-28 14:58

    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.

提交回复
热议问题