如何构建更复杂的单个LINQ to XML查询?

时间:2010-06-02 12:08:54

标签: c# linq-to-xml

我是一名LINQ新手,所以一旦得到答案,以下内容可能会变得非常简单明了,但我不得不承认这个问题正在踢我的屁股。

鉴于此XML:

<measuresystems>
  <measuresystem name="SI" attitude="proud">
    <dimension name="mass" dim="M" degree="1">
      <unit name="kilogram" symbol="kg">
        <factor name="hundredweight" foreignsystem="US" value="45.359237" />
        <factor name="hundredweight" foreignsystem="Imperial" value="50.80234544" />
      </unit>
    </dimension>
  </measuresystem>
</measuresystems>

我可以使用以下LINQ to XML查询千克和美国百分之间的转换因子的值,但是肯定有一种方法可以将四个连续的查询压缩成一个复杂的查询吗?

XElement mss = XElement.Load(fileName);

IEnumerable<XElement> ms =
    from el in mss.Elements("measuresystem")
    where (string)el.Attribute("name") == "SI"
    select el;

IEnumerable<XElement> dim =
    from e2 in ms.Elements("dimension")
    where (string)e2.Attribute("name") == "mass"
    select e2;

IEnumerable<XElement> unit =
    from e3 in dim.Elements("unit")
    where (string)e3.Attribute("name") == "kilogram"
    select e3;

IEnumerable<XElement> factor =
    from e4 in unit.Elements("factor")
    where (string)e4.Attribute("name") == "pound" 
        && (string)e4.Attribute("foreignsystem") == "US"
    select e4;

foreach (XElement ex in factor)
{
    Console.WriteLine ((string)ex.Attribute("value"));
}

1 个答案:

答案 0 :(得分:2)

这可行,只需将它们加在一起:

IEnumerable<XElement> ms =
    from el in mss.Elements("measuresystem")
    where (string)el.Attribute("name") == "SI"
    from e2 in el.Elements("dimension")
    where (string)e2.Attribute("name") == "mass"
    from e3 in e2.Elements("unit")
    where (string)e3.Attribute("name") == "kilogram"
    from e4 in e3.Elements("factor")
    where (string)e4.Attribute("name") == "pound" 
        && (string)e4.Attribute("foreignsystem") == "US"    
    select e4;