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

.net LINQ到XML:如何在for-each循环中添加子元素?,.net,xml,linq-to-xml,.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 /&

上面的代码将创建如下内容:

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>

我需要的是这样的东西:

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>

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


谢谢

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

IOW:

你可以说:

  <One>
    <Two>
      <Three />
    </Two>
  </One>
要获得:

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})
如果要查找树中要开始的最后一个节点(上例中为A3),则需要:

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
root.Descendants().Last()

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

对当前代码做一点小小的更改就可以满足你的要求:

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
root.Descendants().Last()
编辑:

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

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

我相信这就是我想要的。如果此代码在函数中,如果
xml
最终引用最后一个子元素,我将如何返回作为结果构建的整个树?请参阅更新的答案:只需将第一个创建的元素存储在函数不会修改的变量中即可