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 System.Xml.Linq.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 System.Xml.Linq.XElement.Parse, System.Xml.Linq.XDocument.Parse, System.Xml.Linq.XElement.Load, and System.Xml.Linq.XDocument.Load methods to throw, see the XmlReader documentation.

See Also

Concepts

Parsing XML

Build Date:

2012-08-02