Saturday, 15 September 2012

c# - xPath to get sibling value for element with specific value -



c# - xPath to get sibling value for element with specific value -

given xml:

<initresponse> <lottotoken>908ec70b308adf10d04db1478ef9b01b</lottotoken> <gameinfolist> <gameinfo> <draw> <gameid>l649</gameid> <draw>3035</draw> </draw> </gameinfo> <gameinfo> <draw> <gameid>bc49</gameid> <draw>2199</draw> </draw> </gameinfo> </gameinfolist> </initresponse>

i need draw number based on specific gameid. illustration if specify gameid l649 need 3035.

the next works in several online evaluators, not in c#. says cannot find it. suggestions?

class="lang-none prettyprint-override">/initresponse/gameinfolist/gameinfo/draw/draw[preceding-sibling::gameid='l649']

c# code i've tried:

xmlnode node = xmldoc.selectsinglenode("/initresponse/gameinfolist/gameinfo/draw/draw[preceding-sibling::gameid='l649']");

... xmldoc xmldocument object loaded xml. node variable ends null value seems indicate there no match found.

here xpath (with linq)

var xdoc = xdocument.load(path_to_xml); string xpath = "/initresponse/gameinfolist/gameinfo/draw[gameid='l649']/draw"; var draw = xdoc.xpathselectelement(xpath); if (draw != null) // check if draw gameid found in xml value = (int)draw;

also can utilize pure linq xml (but in case xpath looks more compact):

var draw = xdoc.descendants("gameinfo") .selectmany(g => g.elements("draw")) .singleordefault(d => (string)d.element("gameid") == "l649"); if (draw != null) value = (int)draw.element("draw");

c# xml xpath

No comments:

Post a Comment