4

问候!

我正在努力解决 LINQ 问题。如果我将诸如此类的一些 XML 加载到 XDocument 对象中:

<Root>
    <GroupA>
        <Item attrib1="aaa" attrib2="000" attrib3="true" />
    </GroupA>
    <GroupB>
        <Item attrib1="bbb" attrib2="111" attrib3="true" />
        <Item attrib1="ccc" attrib2="222" attrib3="false" />
        <Item attrib1="ddd" attrib2="333" attrib3="true" />
    </GroupB>
    <GroupC>
        <Item attrib1="eee" attrib2="444" attrib3="true" />
        <Item attrib1="fff" attrib2="555" attrib3="true" />
    </GroupC>
</Root>

我想获取 Group 元素的所有 Item 子元素的属性值。这是我的查询的样子:

var results = from thegroup in l_theDoc.Elements("Root").Elements(groupName)
              select new
              { 
                 attrib1_val = thegroup.Element("Item").Attribute("attrib1").Value,      
                 attrib2_val = thegroup.Element("Item").Attribute("attrib2").Value,
              };

查询有效,但如果 groupName 变量包含“GroupB”,则只返回一个结果(第一个 Item 元素)而不是三个。我错过了什么吗?

4

4 回答 4

6
XElement e = XElement.Parse(testStr);

string groupName = "GroupB";
var items = from g in e.Elements(groupName)
            from i in g.Elements("Item")
            select new {
                           attr1 = (string)i.Attribute("attrib1"),
                           attr2 = (string)i.Attribute("attrib2")
                       };

foreach (var item in items)
{
    Console.WriteLine(item.attr1 + ":" + item.attr2);
}
于 2008-09-24T14:01:33.743 回答
2

是的, .Element() 只返回第一个匹配的元素。你想要 .Elements() 并且你需要重新编写你的查询:

var results = from group in l_theDoc.Root.Elements(groupName)
              select new
              {
                  items = from i in group.Elements("Item")
                          select new 
                          {
                              attrib1_val = i.Attribute("attrib1").Value,
                              attrib2_val = i.Attribute("attrib2").Value
                          }
              };
于 2008-09-24T13:58:44.047 回答
1

这是答案的查询方法形式:

var items = 
  e.Elements("GroupB")
    .SelectMany(g => g.Elements("Item"))
    .Select(i => new {
      attr1 = i.Attribute("attrib1").Value,
      attr2 = i.Attribute("attrib2").Value,
      attr3 = i.Attribute("attrib3").Value
    } )
    .ToList()
于 2008-09-24T14:17:59.990 回答
0

另一种可能性是使用 where 子句:

var groupName = "GroupB";
var results = from theitem in doc.Descendants("Item")
              where theitem.Parent.Name == groupName
              select new 
              { 
                  attrib1_val = theitem.Attribute("attrib1").Value,
                  attrib2_val = theitem.Attribute("attrib2").Value, 
              };
于 2008-09-24T14:08:43.460 回答