将后代节点添加到非根父节点

时间:2011-09-06 17:32:54

标签: xml vb.net linq

请注意我是LINQ to XML的新手。

我现在正在尝试将A节点(后代)添加到节点

例如。

由此:

<World>
    <Country Name = "South_Africa"/>
</World>

To This:

<World>
    <Country Name = "South_Africa">
        <Person Name = "Aiden Strydom"/>
    </Country>
</World>

正如您所看到的,我正在尝试将Person节点添加到Country, 但我没有成功

代码:

' Load current document.
Dim XMLDoc As XDocument = XDocument.Load("Test.xml")

' Make new XElement based on incoming parameters.
Dim MyElement As XElement = _
    <Person Name=<%= PersonName %>/>

' Find The Node in Question
Dim e As IEnumerable(Of XElement) = From element
                                    In XMLDoc.Root.Elements("Country")
                                    Where element.Attribute("Name").Value = "South_Africa"
                                    Select element
' Add To it
e.FirstOrDefault().AddFirst(MyElement)

' Save changes to disk.
XMLDoc.Save("Test.xml")

1 个答案:

答案 0 :(得分:1)

您没有指定实际问题,但您似乎将脚本标记与代码混合在一起:

<Person Name=<%= PersonName %>/>

以及不正确创建XElement。我试试这个:

' Load current document.
Dim XMLDoc As XDocument = XDocument.Load("Test.xml")

' Make new XElement based on incoming parameters.
 Dim MyElement As New XElement("Person")

' Add the name as an attribute
MyElement.Add(New XAttribute("name", PersonName)) ' PersonName is the supplied value

' Find The Node in Question
Dim e As XElement = (From element In XMLDoc.Root.Elements("Country")
                     Where element.Attribute("Name").Value = "South_Africa"
                     Select element).FirstOrDefault()

' Add To it
e.AddFirst(MyElement)

' Save changes to disk.
XMLDoc.Save("Test.xml")

这将采用输入XML:

<World>
    <Country Name = "South_Africa"/>
</World>

并生成:

<World>
    <Country Name = "South_Africa">
        <Person Name = "Aiden Strydom"/>
    </Country>
</World>

假设上面代码中的PersonName =“Aiden Strydom”。