gpt4 book ai didi

c# - 查找 XML 中关键字的计数

转载 作者:行者123 更新时间:2023-11-30 23:25:14 26 4
gpt4 key购买 nike

Xml 可以有这样的格式

<root>
<child1>
Value1
</child1>
<child2>
<child3>
Value2
</child3>
<child4>
<child5>
Value1
</child5>
</child4>
</child2>
<child6>
Value1
</child6>
</root>

这里Value1写了3次,所以count应该是3

或者 Xml 可以有这样的格式:

<root>
<child1 value="Value1" />
<child2 value="Value2"/>
<child3 value="Value1" />
<child4 value="Value1"/>
<child5 value="Value3" />
<child6 value="Value4"/>
</root>

此处 Value1 的计数为 3。

所以 Xml 可以有任何格式,我想计算 xml 中特定关键字的数量。

请指导!

Edit: The question is not possible duplicate of the link you have mentioned, here I don't know the depth of the xml e.g. it could have one child or many children in which a keyword may or may not present. I want to traverse all the nodes without know the depth of each node**

最佳答案

我建议为此使用 XDocument

XDocument doc = XDocument.Load(filename);       
var count = doc.Descendants() // flattens the structure
.Where(x=> (!x.HasElements &&((string)x.Value).Trim() == "Value1")
|| (x.Attribute("value") != null
&& x.Attribute("value").Value == "Value1")
) // filter based on value
.Count(); // Take count

检查这个Demo

关于c# - 查找 XML 中关键字的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37428138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com