Export (0) Print
Expand All

How to: Catch Parsing Errors

This topic shows how to detect badly formed or invalid XML.

LINQ to XML is implemented using XmlReader. If badly formed or invalid XML is passed to LINQ to XML, the underlying XmlReader class will throw an exception. The various methods that parse XML, such as XElement.Parse, do not catch the exception; the exception can then be caught by your application.

Note that you cannot get parse errors if you use XML literals. The Visual Basic compiler will catch errors of badly formed or invalid XML.

The following code tries to parse invalid XML:

try {
    XElement contacts = XElement.Parse(
        @"<Contacts>
            <Contact>
                <Name>Jim Wilson</Name>
            </Contact>
          </Contcts>");

    Console.WriteLine(contacts);
}
catch (System.Xml.XmlException e)
{
    Console.WriteLine(e.Message);
}

When you run this code, it throws the following exception:

The 'Contacts' start tag on line 1 does not match the end tag of 'Contcts'. Line 5, position 13.

For information about the exceptions that you can expect the XElement.Parse, XDocument.Parse, XElement.Load, and XDocument.Load methods to throw, see the XmlReader documentation.

Show:
© 2015 Microsoft