SelectSingleNode() with XPath C# Failure

2.8k views Asked by At

i got a XML File as export from Wireshark and want to select the Number of the actual frame

The structure of this file is like this

<packet>
    <proto>
        ...
    </proto>
    ....
    <proto>
        <field name="frame.number" show="1">
    </proto>
</packet>
<packet>
    <proto>
        ...
    </proto>
    ....
    <proto>
        <field name="frame.number" show="2">
    </proto>
</packet>

...and so on...

I use this code to select the packets/fields

XmlNodeList packages = xmlDoc.SelectNodes("//packet");
foreach (XmlNode packet in packages) {
    string frameNumber = packet.SelectSingleNode("//field[@name='frame.number']").
        Attributes["show"].Value;
    Console.WriteLine(frameNumber);
}

If I Debug through the code, it always selects the right Nodes with the correct attributes. But at each iteration there is a "1" printed out.

Does anyone suspect what failure this is? I didn't found anything on the internet for this failure

Thank you very much!!

1

There are 1 answers

1
Jamiec On BEST ANSWER

Its because your XPath in SelectSingleNode starts with // - which means "start from the root of the document". Therefore you're always getting the first one.

Just change the XPath in that method to proto/field[@name='frame.number'].