Aiden Strydom
Aiden Strydom

Reputation: 1208

Add Descendant Node to Non-Root Parent

Please note i am new to LINQ to XML.

I am now trying to add A node(descendant) TO a Node

eg.

From this:

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

To This:

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

As you can see i am trying to add a Person node to Country, but i am not succeeding

Code:

' 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")

Upvotes: 1

Views: 845

Answers (1)

Tim
Tim

Reputation: 28530

You didn't specify what the actual issue is, but you appear to be mixing script markup with code:

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

As well as not creating the XElement properly. I'd try this:

' 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")

This will take the input XML:

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

And generate:

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

Assuming PersonName in the code above = "Aiden Strydom".

Upvotes: 1

Related Questions