虽然我有一些使用 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);}
这个解决方案似乎只计算最大数量的属性。
如有任何帮助,我们将不胜感激。
最佳答案
我会对文档中的所有元素进行循环,然后计算每个元素的属性:
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/