user67144
user67144

Reputation: 13

Foreach Accessing XML elements inside nodes

I have the following XML elements in a big file and I am trying to iterate thru the elements inside StayDateRange how can I accomplish this? I have other sections where I need to do something similar.

<StDteRange timeUnitType="DAY">
   <strtTime>2009-06-28T00:00:00.000</strtTime>
   <numOfUnits>4</numOfUnits>
</StDteRange >

IEnumerable<XElement> StDteRange = from el in root.Descendants(aw + "StDteRange ") 
select  el;

foreach (XElement el in StDteRange )
{
       if (el.Name.LocalName=="strtTime")
            Console.WriteLine((DateTime)el);

       if (el.Name=="numOfUnits")
            Console.WriteLine((int)el);
}

Upvotes: 0

Views: 359

Answers (1)

John
John

Reputation: 6553

There are some good examples online:

Scott Guthrie's Blog - Using Linq to XML

Hooked On Linq - Linq to XML

You can create a simple class to hold your results and then in your linq query create new objects:

public class XMLResult()
{
    public string localname;
    public int Units;
}

IEnumerable<XMLResult> results = from el in root.Descendants(aw + "StDteRange ") 
     select new XMLResult() {
          Name = el.Element("strtTime").value,
          Units = el.Element("numOfUnits").value
     };

Upvotes: 1

Related Questions