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.
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