LINQ to XML:如何在for-each循环中添加子元素?

时间:2009-08-04 11:24:56

标签: .net xml linq-to-xml

Dim names() As String = {"one", "two", "three"}
Dim xml As XElement = Nothing
For Each name In names
  If xml Is Nothing Then
    xml = New XElement(name)
  Else
    xml.Add(New XElement(name)
  End If
Next

以上代码将创建如下内容:

  <One>
    <Two />
    <Three />
  </One>

我需要的是这样的事情:

  <One>
    <Two>
      <Three />
    </Two>
  </One>

我尝试使用xml.Elements.Last.Add(New XElement(name)),但Last方法由于某种原因未必返回最后一个元素。

谢谢!

2 个答案:

答案 0 :(得分:3)

对当前代码进行一些小改动即可实现您的目标:

Dim names() As String = {"one", "two", "three"}
Dim xml As XElement = Nothing
For Each name In names
  Dim new_elem As New XElement(name)
  If xml IsNot Nothing Then
      xml.Add(new_elem)
  End If
  xml = new_elem
Next

修改

您可以引入另一个变量来存储根元素:

Function BuildTree() As XElement
    Dim tree As XElement = Nothing

    Dim names() As String = {"one", "two", "three"}
    Dim xml As XElement = Nothing
    For Each name In names
        Dim new_elem As New XElement(name)
        If tree Is Nothing Then
            tree = new_elem
        Else
            xml.Add(new_elem)
        End If
        xml = new_elem
    Next

    Return tree
End Function

答案 1 :(得分:0)

看起来你只想要add on an XElement - 不要使用.Last或其他任何东西,在最后一个之后添加是默认行为..

IOW:

你可以说:

Dim node1 as XElement = new XElement( "A1")
Dim node2 as XElement = new XElement( "A2")
Dim node3 as XElement = new XElement ("A3")
node2.Add( node3)
Dim root as XElement = new XElement("Root",new XElement(){node1,node2})

获得:

<Root>
  <A1 />
  <A2>
    <A3 />
  </A2>
</Root>

或者做同样的事情:

Dim node1 as XElement = new XElement( "A1")
Dim node2 as XElement = new XElement( "A2")
Dim node3 as XElement = new XElement ("A3")
Dim root as XElement = new XElement("Root")
Dim children as XElement() = new XElement(){node1,node2}
for each child in children 
    root.add( child)
    if child.Name = "A2"
        child.Add( node3)
    end if
next

如果您正在寻找树中的最后一个节点(上例中的A3),您需要:

root.Descendants().Last()

这就是你真正想要的东西(当提出问题时,最好给一棵树并说出你要隔离哪些节点)?