Saturday, 15 February 2014

xml - Find an Attribute based off Attribute in same element using XmlDocument -



xml - Find an Attribute based off Attribute in same element using XmlDocument -

i looking loop thru element based off 1 attribute, "sequence" , retrieve another, "strokes".

my xml follows:

<tournament> <leaderboard> <player first_name="jimmy" last_name="walker" country="united states" id="2db60f6e-7b0a-4daf-97d9-01a057f44f1d" position="1" money="900000.0" points="500.0" score="-17" strokes="267"> <rounds> <round score="-1" strokes="70" thru="18" eagles="0" birdies="5" pars="9" bogeys="4" double_bogeys="0" other_scores="0" sequence="1"/> <round score="-2" strokes="69" thru="18" eagles="0" birdies="3" pars="14" bogeys="1" double_bogeys="0" other_scores="0" sequence="2"/> <round score="-9" strokes="62" thru="18" eagles="0" birdies="10" pars="7" bogeys="1" double_bogeys="0" other_scores="0" sequence="3"/> <round score="-5" strokes="66" thru="18" eagles="0" birdies="6" pars="11" bogeys="1" double_bogeys="0" other_scores="0" sequence="4"/> </rounds> </player> </leaderboard> </tournament>

i able retrieve individual round elements based on next code:

// edited reflect solution

foreach (xmlnode player in doc.getelementsbytagname("player")) { string strokes; dtattributelist.rows.add( player.attributes["last_name"].value, player.attributes["first_name"].value, player.attributes["position"].value, player.attributes["score"].value); if (player.haschildnodes) { foreach (xmlnode round in player.lastchild) { strokes = round.attributes["strokes"].value; dtattributelist.rows.add(strokes); } } }

however in doing able retrieve first element , values.

please help me find solution loop thru "round" elements either via filter on sequence or loop of sort.

it's much easier utilize xpath approach you've tried above. you're creating huge amount of duplicate code using for loop instead of foreach:

foreach (xmlnode player in doc.getelementsbytagname("player")) { string strokes; dtattributelist.rows.add( player.attributes["last_name"].value, player.attributes["first_name"].value, player.attributes["position"].value, player.attributes["score"].value); foreach (xmlnode round in player.selectnodes("rounds/round")) { strokes = round.attributes["strokes"].value; dtattributelist.rows.add(strokes); } }

if need iterate throug them based on order of sequence (and they're not in order), can this:

var rounds = player.selectnodes("rounds/round") .oftype<xmlnode>() .orderby(n => int.parse(n.attributes["sequence"].value)); foreach (xmlnode round in rounds) { // ... }

xml xml-parsing

No comments:

Post a Comment