Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This article shows how to detect badly formed or invalid XML in C# or Visual Basic.
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, don't catch the exception; the exception can then be caught by your application.
Example: Parse 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);
}
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
Because of the invalid end tag </Contcts>, the example throws the following exception:
The 'Contacts' start tag on line 1 doesn't match the end tag of 'Contcts'. Line 5, position 13.
For information about the exceptions that the XElement.Parse, XDocument.Parse, XElement.Load, and XDocument.Load methods throw, see the XmlReader documentation.