Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through XmlNodeList, value is always the same

Tags:

c#

xml

xpath

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?

like image 205
lethallynx Avatar asked May 24 '11 15:05

lethallynx


1 Answers

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()

like image 72
Mongus Pong Avatar answered Nov 16 '22 01:11

Mongus Pong