none
Get xml element by index RRS feed

  • Question

  • Is there anyway of getting a specific row from a bunch of XML by index. 

    <ITINERARY>
        <ROW>1,Tue,20 Apr 2010,FLT,KQ 101 LHR NBO 2000#0630,1,Economy,KQ,2,0,0,-,-,-,Confirmed</ROW>
        <ROW>2,Wed,21 Apr 2010,FLT,KQ 602 NBO MBA 0830 0930,0,Economy,KQ,2,0,0,-,-,-,Confirmed</ROW>
        <ROW>4,Wed,21 Apr 2010,HTL,SERENA BEACH HOTEL & SPA,7,Half Board,VILLAGE ROOM,2,0,0,1,0,0,Confirmed</ROW>
        <ROW>5,Wed,28 Apr 2010,FLT,KQ 615 MBA NBO 2000 2100,0,Economy,KQ,2,0,0,-,-,-,Confirmed</ROW>
        <ROW>6,Wed,28 Apr 2010,FLT,KQ 102 NBO LHR 2345#0645,1,Economy,KQ,2,0,0,-,-,-,Confirmed</ROW>
    </ITINERARY>

    I want to say get the third row i.e.: <ROW>4,Wed,21 Apr 2010,HTL,SERENA BEACH HOTEL & SPA,7,Half Board,VILLAGE ROOM,2,0,0,1,0,0,Confirmed</ROW>

    Currently I am using a loop - but I am hoping Linq has a method for this?
    Thursday, January 7, 2010 4:06 PM

Answers

  • XElement it = XElement.Load("input.xml");
    XElement row3 = it.Elements("ROW").ElementAt(2); // index starts with zero

    Note that ElementAt(index) throws an exception when no item with that index exists.
    MVP XML My blog
    • Marked as answer by TheLearner Thursday, January 7, 2010 5:09 PM
    Thursday, January 7, 2010 4:19 PM

All replies

  • XElement it = XElement.Load("input.xml");
    XElement row3 = it.Elements("ROW").ElementAt(2); // index starts with zero

    Note that ElementAt(index) throws an exception when no item with that index exists.
    MVP XML My blog
    • Marked as answer by TheLearner Thursday, January 7, 2010 5:09 PM
    Thursday, January 7, 2010 4:19 PM
  • Your XML is invalid the "HOTEL & SPA" on the 3rd row is invalid piece of XML text. You need "HOTEL &apm; SPA" instead...

    Assuming LINQ to XML and C# you can use the Skip method like this:
                XDocument doc = XDocument.Parse(xml);
                Console.WriteLine(doc.Root.Elements("ROW").Skip(2).First());
    Thanks,
    Vitek Karas [MSFT]
    Thursday, January 7, 2010 4:21 PM
    Moderator