迭代XmlNodeList,值始终相同
我有以下 XML:
<xmlRequest>
<stats>
<match mid='40704828'>
<match_stats>
<ms aid='254664' cli_name='Hero_Engineer'>
<stat name='nickname'>lethallynx</stat>
<stat name='level'>11</stat>
</ms>
<ms aid='354522' cli_name='Hero_Devourer'>
<stat name='nickname'>AbendrothA</stat>
<stat name='level'>12</stat>
</ms>
</match_stats>
</match>
</stats>
</xmlRequest>
我正在尝试使用下面的代码提取 nickName 和 level 的值:
XmlNodeList nodeList = doc.SelectNodes("//ms");
List<string> myList = new List<string>();
foreach (XmlNode node in nodeList)
{
XmlNode nodeNickName = node.SelectSingleNode("//stat[@name='nickname']/text()");
mylist.Add(nodeNickName.Value);
}
问题是,虽然我可以看到节点对象正在使用下一组数据进行更新,但返回的值始终与第一个数据集相同昵称。
因此,nodeNickName.Value 始终等于“lethallynx”。
有什么想法吗?
I have the following XML:
<xmlRequest>
<stats>
<match mid='40704828'>
<match_stats>
<ms aid='254664' cli_name='Hero_Engineer'>
<stat name='nickname'>lethallynx</stat>
<stat name='level'>11</stat>
</ms>
<ms aid='354522' cli_name='Hero_Devourer'>
<stat name='nickname'>AbendrothA</stat>
<stat name='level'>12</stat>
</ms>
</match_stats>
</match>
</stats>
</xmlRequest>
I am trying to extract the value of nickName and level using the code below:
XmlNodeList nodeList = doc.SelectNodes("//ms");
List<string> myList = new List<string>();
foreach (XmlNode node in nodeList)
{
XmlNode nodeNickName = node.SelectSingleNode("//stat[@name='nickname']/text()");
mylist.Add(nodeNickName.Value);
}
The problem is that while I can see the node object being updated with next set of data the value returned is always the same as the first nickname.
So nodeNickName.Value is always equal to "lethallynx".
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
//stat[@name='nickname']/text()
xpath 查询中的//
选择根节点并从那里向下搜索。您应该将其替换为
./
,它从当前节点进行搜索,如./stat[@name='nickname']/text()
The
//
in your//stat[@name='nickname']/text()
xpath query selects the root node and searches down from there.You should replace this with a
./
, which takes the search from the current node, as./stat[@name='nickname']/text()
在您的
foreach
中尝试:In your
foreach
try: