c# - 检查 LINQ to XML 中的单独节点

标签 c# .net linq linq-to-xml

如何确定标签是否为以下格式:<Closed />在 Linq To XML 中?

最佳答案

您可以使用 XElement.IsEmpty property .请注意 IsEmpty 检查的内容,如链接的 MSDN 页面上的注释所定义:

Note that an element that contains a start and end tag with no content between the tags is not considered to be an empty element. It has content with no length. Only an element that contains only a start tag, and is expressed as a terminated empty element, is considered to be empty.

为了说明,请考虑以下示例:

var xml = XElement.Parse(@"<root>
    <pair>foo</pair>
    <pair></pair>
    <single id=""42"" />
    <single />
</root>");

foreach (var element in xml.Elements())
{
    Console.WriteLine("{0}: {1}", element.IsEmpty, element);
}

// False: <pair>foo</pair>
// False: <pair></pair>
// True: <single id="42" />
// True: <single />

如果要检查节点 IsEmpty 并且没有属性,请添加检查 element.Attributes().Any() 是否为 false

关于c# - 检查 LINQ to XML 中的单独节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4664232/

相关文章:

c# - 托管在 Windows 服务中的 WCF 服务运行速度比控制台应用程序慢 10 倍

c# - 如何获取特定月份和年份的天数?

c# - 从 Linq Group By 输出 2 个字段

c# - 如何使用此示例的 htmlagilitypack 从 HTML 中提取文本?

c# - 如何使用 ADO.Net 最好地插入 350,000 行

c# - 如何为此进行 LINQ 查询?

c# - 如何将文件的缩略图提取到 .NET 中的图像文件中?

c# - Asp .Net Gridview 分页

c# - 有没有办法指定范围?

c# - 为什么英语(加勒比海)的文化名称是 "en-029"?