如何:捕捉分析错误

更新:November 2007

本主题演示如何检测格式不正确或无效的 XML。

LINQ to XML 通过使用 XmlReader 实现。如果将格式不正确或无效的 XML 传递给 LINQ to XML,则基础 XmlReader 类将引发异常。用于分析 XML 的各种方法(如 XElement.Parse)不会捕捉异常;应用程序可以捕捉异常。

请注意,如果使用 XML 文本,则无法获取分析错误。Visual Basic 编译器将捕捉格式不正确或无效的 XML 错误。

示例

下面的代码尝试分析无效的 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

运行此代码时,会引发以下异常:

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

有关 XElement.ParseXDocument.ParseXElement.LoadXDocument.Load 方法可能会引发的异常的更多信息,请参见 XmlReader 文档。

请参见

概念

分析 XML