使用LINQ Group By选择XElement的子节点

时间:2014-09-21 15:59:40

标签: xml vb.net linq xelement

我在表单中有一些xml:

<Test>
  <Parent Value1="1" Value2="2">
    <Child value3="x"/>
  </Parent>
  <Parent Value1="1" Value2="2">
    <Child value3="y"/>
  </Parent>
  <Parent Value1="a" Value2="b">
    <Child value3="z"/>
  </Parent>
</Test>

我正在尝试使用xelements和linq对具有相同属性值的父节点下的子节点进行分组。 E.g:

<Test>
  <Parent Value1="1" Value2="2">
    <Child value3="x"/>
    <Child value3="y"/>
  </Parent>
  <Parent Value1="a" Value2="b">
    <Child value3="z"/>
  </Parent>
</Test>

到目前为止,这就是我所拥有的:

    Dim l_xeXML As XElement = <Test>
                                  <Parent Value1="1" Value2="2">
                                      <Child value3=""/>
                                  </Parent>
                                  <Parent Value1="1" Value2="2">
                                      <Child value3=""/>
                                  </Parent>
                                  <Parent Value1="a" Value2="b">
                                      <Child value3=""/>
                                  </Parent>
                              </Test>

    Dim l_xeGROUPED As XElement = <Test>
                                      <%= From l_xeExample As XElement In l_xeXML...<Parent>
                                          Group l_xeExample By Key = New With {Key l_xeExample.@Value1, Key l_xeExample.@Value2} Into Group
                                          Select l_GROUPED = New With {.Value1 = Key.Value1, .Value2 = Key.Value2}
                                          Select <Parent Value1=<%= l_GROUPED.Value1 %> Value2=<%= l_GROUPED.Value2 %>>
                                                     <!-- Can't work out what to put here -->
                                                 </Parent> %>

                                  </Test>

    Debug.Print(l_xeGROUPED.ToString)

<!-- Can't work out what to put here -->行上,我尝试了<%= l_xeExample.<Child> %>但是我收到一条错误消息,说明l_xeExample不在范围内。

有人可以帮忙吗?

提前致谢

1 个答案:

答案 0 :(得分:1)

这将产生所需的输出:

.......
.......
Dim l_xeGROUPED As XElement = 
    <Test>
          <%= From l_xeExample As XElement In l_xeXML...<Parent>
              Group l_xeExample By Key = New With {Key l_xeExample.@Value1, Key l_xeExample.@Value2} 
              Into Parent = Group
              Select <Parent Value1=<%= Key.Value1 %> Value2=<%= Key.Value2 %>>
                         <%= From g As XElement In Parent.<Child>
                             Select g
                         %>
                     </Parent> %>
      </Test>
Debug.Print(l_xeGROUPED.ToString)