此示例代码演示如何在LINQ to XML时捕获异常信息。
示例代码
此代码是调用XElement.Parse()方法分析所提供的XML字符串,但是因为此XML字符串中的开始标记<Contacts>和结束标记</Contcts>不是一致的,因此产生了分析异常。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml;
namespace Demo04
{
class Program
{
static void Main(string[] args)
{
try
{
XElement Contacts = XElement.Parse(
@"<Contacts>
<Contact>
<Name>Jim Wilson</Name>
</Contact>
</Contcts>");
Console.WriteLine(Contacts);
}
catch (XmlException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
[代码]捕获分析错误(LINQ to XML)
最新推荐文章于 2025-07-26 13:11:15 发布
本文演示了在使用LINQ to XML解析不正确的XML字符串时如何捕获并处理XmlException异常。通过一个示例代码说明了当XML字符串的开始标记与结束标记不匹配时,程序如何捕获异常并输出异常信息。
37

被折叠的 条评论
为什么被折叠?



