简体   繁体   中英

SelectSingleNode() with XPath C# Failure

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!!

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'] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM