我想计算 XML 文档中的属性。没有它运行良好。但是在评论中我得到了一个例外:
System.NullReferenceException: '未将对象引用设置为对象的实例。'
可以用其他方式计算吗?或者为什么计数方法不忽略 xml 示例中的注释行?
XmlDocument doc = new XmlDocument();
doc.LoadXml(@"
<ListOfMegaCities>
<MegaCities city=""Moscow"" residents=""11503501"" foundation=""1624""/>
<MegaCities residents=""8336817""/> <!-- comment test -->
<MegaCities foundation=""1066"" city=""London""/>
</ListOfMegaCities>");
XmlNodeList elemList = doc.GetElementsByTagName("ListOfMegaCities");
Console.Write("\nCount Attributes: " + elemList[0].ChildNodes[0].Attributes.Count);
Console.Write("\nCount Attributes: " + elemList[0].ChildNodes[1].Attributes.Count);
Console.Write("\nCount Attributes: " + elemList[0].ChildNodes[2].Attributes.Count);
最好使用 LINQ to XML API。自 2007 年以来,它在 .Net Framework 中可用。
一个单一的语句给出了没有任何循环的答案。
C#
void Main()
{
XDocument xdoc = XDocument.Parse(@"<ListOfMegaCities>
<MegaCities city='Moscow' residents='11503501' foundation='1624'/>
<MegaCities residents='8336817'/> <!-- comment test -->
<MegaCities foundation='1066' city='London'/>
</ListOfMegaCities>");
int AttributeCounter = xdoc.Descendants("MegaCities")
.Attributes().Count();
Console.WriteLine("Total attributes counter: {0}", AttributeCounter);
}
输出
Total attributes counter: 6
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句