Foreach访问节点内的XM​​L元素

时间:2011-11-04 15:41:14

标签: c# linq foreach

我在一个大文件中有以下XML元素,我试图通过StayDateRange中的元素进行迭代,如何实现这一目标?我有其他部分需要做类似的事情。

<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);
}

1 个答案:

答案 0 :(得分:1)

网上有一些很好的例子:

Scott Guthrie's Blog - Using Linq to XML

Hooked On Linq - Linq to XML

您可以创建一个简单的类来保存结果,然后在您的linq查询中创建新对象:

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
     };