Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XDocument.Parse Success or Failure?

Tags:

c#

linq

I am using

XDocument doc = XDocument.Parse(somestring);

But how do I validate if the string somestring is a well formed XML. Is Try Catch the only way to do this?

like image 257
Flood Gravemind Avatar asked Oct 22 '13 17:10

Flood Gravemind


2 Answers

Is Try Catch the only way to do this?

There is no TryParse method for XDocument, so try-catch is probably the best bet. Also consider validating your XML against a schema since it will not only check if the XML is well-formed, but also checks for constraints.

You may see: Validation Against XML Schema (XSD) with the XmlValidatingReader

like image 92
Habib Avatar answered Oct 19 '22 12:10

Habib


If you only need to check whether the document is well-formed, the fastest way is to use XmlReader as follows:

var isWellFormedXml = true;
try
{
    using (var reader = XmlReader.Create(stream)) // can be a mem stream for string validation
    {
        while (reader.Read()) {}
    }
}
catch
{
    isWellFormedXml = false;
}

This way you don't spend memory for XDocument DOM. BTW, XDocument.Parse() uses XmlReader for processing XML, so the exceptions are the same, if you need to analyse them.

like image 28
JustAndrei Avatar answered Oct 19 '22 12:10

JustAndrei