How do I test if XML is well formed using .Net API?
Well-formed means – The XML code must be syntactically correct or the XML parser will raise an error. However it still may not be ‘Valid’ especially if it has a schema associated with it. If you want to just test for Well-formed xml without testing for validity, there is no API for doing this except to encapsulate the code in try-catch which will automatically throw an exception if the xml is not Well-Formed. Here is a simple example:
XmlTextReader reader = new XmlTextReader(...);
try
{
while (reader.Read());
//XML is ok
}
catch (Exception e)
{
//Malformed XML }
Otherwise the XmlValidatingReader class can be used to test both for Well-Formed XML and Valid XML.
Back to
XML FAQ