Skip to main content
 首页 » 编程设计

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

2024年02月13日14zhujiabin

虽然我有一些使用 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() 
    ); 
}