Share via


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.

Example

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);
}
Try
    Dim contacts As XElement = XElement.Parse("<Contacts>" & vbCrLf & _
        "    <Contact>" & vbCrLf & _
        "        <Name>Jim Wilson</Name>" & vbCrLf & _
        "    </Contact>" & vbCrLf & _
        "</Contcts>")

    Console.WriteLine(contacts)
Catch e As System.Xml.XmlException
    Console.WriteLine(e.Message)
End Try

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.

See Also

Concepts

Parsing XML