如何计算节点并在XML C#中的createtextnode中显示 [英] How do I count the node and display in the createtextnode in XML C#
问题描述
<root>
<total>
<rec>
<datas>
<data>
<ic>22
<amount>44
</data>
<data>
<ic>33
<amount>20
</data>
<data>
<ic>44
<amount>10
</data>
XML布局与我输入的不同,希望你能理解。
1个根节点有2个不同的节点(总数和数据)。但是我想计算数据中节点的数量并显示在总节点的文本上。
我尝试过:
int count = doc.SelectNodes(root / total / data)。Count;
XmlNode total = doc.CreateElement(total_rec);
total.AppendChild(doc.CreateTextNode(count));
scannernode.AppendChild(总计);
输出:0,右边应该是3.我该怎么办?
XML layout is different from what I type, hope you can understand.
1 root node has 2 different node (total and data). However I want to count number of node in data and display on the total node's text.
What I have tried:
int count = doc.SelectNodes("root/total/data").Count;
XmlNode total= doc.CreateElement("total_rec");
total.AppendChild(doc.CreateTextNode(count));
scannernode.AppendChild(total);
Output: 0, by right should be 3. How am I suppose to do?
推荐答案
这将返回3的计数:
This will return a count of 3:
var rawXml = @"<root>
<total>
<rec>
<datas>
<data>
<ic>22</ic>
<amount>44</amount>
</data>
<data>
<ic>33</ic>
<amount>20</amount>
</data>
<data>
<ic>44</ic>
<amount>10</amount>
</data>
</datas>
</rec>
</total>
</root>";
var doc = XDocument.Parse(rawXml);
var count = doc
.Descendants()
.Select(x => x.Elements("data"))
.FirstOrDefault(x => x.Any())?.Count() ?? 0;
更新:上述解决方案可以进一步简化:
UPDATE: The above solution can be simplified further:
var count = doc
.Descendants()
.SelectMany(x => x.Elements("data"))?.Count() ?? 0;
此外,如果您遇到 Null Conditional?。 [ ^ ]或 null coalescing ?? [ ^ ],您可以使用以下内容:
Also, if you're experiencing errors with the Null Conditional ?.[^] or the null coalescing ??[^], you can use the following:
var elements = doc.Descendants().SelectMany(x => x.Elements("data"));
var count = elements == null ? 0 : elements.Count();
更新#2:如指出在下面,这可以进一步简化,无需空检查:
UPDATE #2: As pointed out below, this can be simplified further with no need for null checking:
var count = doc.Descendants("data").Count();
这篇关于如何计算节点并在XML C#中的createtextnode中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!