c# - 计算 XML 元素中属性的数量

标签 c# xml linq

虽然我有一些使用 C# 的经验,但我才刚刚开始使用 LINQ。目前使用 LINQPad 4。

我正在尝试计算 XML 文档中每个元素的属性数。

这是我已经得到的,它是 LINQPad 中的样本和已经对该主题进行的研究的混合体。我正在寻找的是使这项工作有效的方法或更好的方法。

XElement config = XElement.Parse (
@"<configuration>
<client enabled='1' enabled2='0' enabled3='1'>
    <timeout>30</timeout>
</client>
<client enabled='true'>
    <timeout>30</timeout>
    <timeout>30</timeout>
</client>
</configuration>");


foreach (XElement child in config.Elements()){
Console.WriteLine("Start");
int attNumbers = config.Descendants().Attributes().Select(att => att.Name).Distinct(). Count();
Console.WriteLine(attNumbers);}

这个解决方案似乎只计算最大数量的属性。

如有任何帮助,我们将不胜感激。

研究: http://social.msdn.microsoft.com/Forums/en-US/8379f0d4-a4f1-41ec-9f45-4573dba81efe/count-number-of-elements-and-attributes-using-linq

最佳答案

我会对文档中的所有元素进行循环,然后计算每个元素的属性:

foreach (var element in config.DescendantsAndSelf())
{
    Console.WriteLine("{0}: {1} attributes", 
        element.Name, 
        element.Attributes().Count()
    );
}

关于c# - 计算 XML 元素中属性的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17678384/

相关文章:

c# - 将 JSON 字符串粘贴到 Visual Studio 中

LINQ递归函数?

c# - 数据表分组,用逗号分隔

c# - native Xamarin.Android 应用程序在 Release模式下不断崩溃

c# - 如何从 C# 发送 POST json 到 asp.net web api

c# - 有直接打印数组的实用程序吗?

python - xml.etree.ElementTree.ParseError -- 异常处理未捕获错误

xml - 正则表达式匹配打开和关闭标签以及该标签内的特定文本模式

xml - VS Code XML 自动格式化

c# - 从通用 List<t> 中删除项目