简体   繁体   中英

XDocument.Parse Success or Failure?

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM