views:

75

answers:

1

Hi Using linq xml in c# how would I extract in for a given predecessor of SetSeg with a certain value in

Eg seatseg num =10 the following Seatassignment loc=??

<top> 
 <SeatSeg>
                  <Num>9</Num>
  </SeatSeg>
  <SeatAssignment>
                  <Loc>032A</Loc>
  </SeatAssignment>
  <SeatSeg>
                  <Num>10</Num>
  </SeatSeg>
  <SeatAssignment>
                  <Loc>033A</Loc>
  </SeatAssignment>
</top>
+1  A: 

I ran this and it writes out 032A.

string xml = "<top><SeatSeg><Num>9</Num></SeatSeg><SeatAssignment><Loc>032A</Loc></SeatAssignment><SeatSeg><Num>10</Num></SeatSeg><SeatAssignment><Loc>033A</Loc></SeatAssignment></top>";
int seatNum = 10;
XDocument xDoc = XDocument.Parse(xml);

string seatLoc = (from seatSeg in xDoc.Element("top").Elements("SeatSeg")
                  where seatSeg.Element("Num").Value == seatNum.ToString() 
                  select seatSeg
                 ).Single().ElementsBeforeSelf().Last().Element("Loc").Value;

Console.WriteLine(seatLoc);

However, looking at the xml, it seems like the following which prints out 033A is what you want

string xml = "<top><SeatSeg><Num>9</Num></SeatSeg><SeatAssignment><Loc>032A</Loc></SeatAssignment><SeatSeg><Num>10</Num></SeatSeg><SeatAssignment><Loc>033A</Loc></SeatAssignment></top>";
int seatNum = 10;
XDocument xDoc = XDocument.Parse(xml);

string seatLoc = (from seatSeg in xDoc.Element("top").Elements("SeatSeg")
                  where seatSeg.Element("Num").Value == seatNum.ToString() 
                  select seatSeg
                 ).Single().ElementsAfterSelf().First().Element("Loc").Value;

Console.WriteLine(seatLoc);

ElementsBeforeSelf() will pull all the preceding siblings. Last() will get the last of the sequence.

Conversely, ElementsAfterSelf() will pull all the subsequent siblings. First() will get the first of the sequence.

rchern
Thanks Rchem, you were right the second example was exactly what I needed! I'm new to c# and Linq :) Could I ask if I need to extend this to deal with the following senario how would I approach it? <top> <SeatSeg> <Num>10</Num> </SeatSeg> <SeatAssignment> <Loc>033A</Loc> </SeatAssignment> <SeatSeg> <Num>10</Num> </SeatSeg><SeatAssignment> <Loc>033B</Loc> </SeatAssignment> </top>looking to return both 033A and 033B as Num is 10 for both.thank you for your help
I_Need_help