Adding Nodes to an XML String

Posted Thu, Aug 20 2009 15:49 by Deborah Kurata

I have an XML string as follows:

<States>
  <State name="Wisconsin">
    <Regions>
      <Region name="Milwaukee">
        <Area name="Mukwanago"/>
        <Area name="Germantown"/>
      </Region>
      <Region name="Fox Valley">
        <Area name="Oshkosh" />
        <Area name="Appleton" />
      </Region>    
    </Regions>
  </State>
</States>

I now want to add another area under Milwaukee called "Wauwatosa".

The code to accomplish this task is as follows.

In C#:

// Be sure to set a reference to System.Core and System.Xml.Linq
XElement states  = XElement.Load("testXML.xml");

// New element under the Milwaukee region
XElement newElement  = XElement.Parse(@"<Area name='Wauwatosa'/>");

// Find the desired parent element
// Using LINQ
XElement parentNode;
var parentQuery = from XElement r in states.Descendants("Region")
                   where r.Attribute("name").Value == "Milwaukee"
                   select r;
parentNode = parentQuery.FirstOrDefault();

// Using Lambda expression
parentNode = states.Descendants("Region").
     Where(r => r.Attribute("name").Value ==
               
"Milwaukee").FirstOrDefault();

if (parentNode != null)
     parentNode.Add(newElement);

states.Save("Revised.xml");

In VB:

' Be sure to set a reference to System.Core and System.Xml.Linq
Dim states As XElement = XElement.Load("testXML.xml")

' New element under the Milwaukee region
Dim newElement As XElement = <Area name="Wauwatosa"/>

' Find the desired parent element
' Using LINQ
Dim parentNode As XElement
Dim parentQuery = From r As XElement In states...<Region> _
                  Where r.@<name> = "Milwaukee"
parentNode = parentQuery.FirstOrDefault()

' Using Lambda expression
parentNode = states...<Region>.Where(Function(r) r.@<name> =  _
                                    
"Milwaukee").FirstOrDefault

If (parentNode IsNot Nothing) Then
    parentNode.Add(newElement)
End If

states.Save("Revised.xml")

This code first loads in the XML file containing the XML at the top of this post. The code then defines the new element for Wauwatosa using XML literals in VB and the XElement properties and methods in C#.

NOTE: The XElement Descendants property works in VB as well.

The next set of code can be done using LINQ or using Lambda expressions. Use either one, but not both. :-)

If the appropriate parent element was found, the new element is added to it. The Add method adds the element as a child element.

Finally, the code saves the revised XML:

<States>
  <State name="Wisconsin">
    <Regions>
      <Region name="Milwaukee">
        <Area name="Mukwanago" />
        <Area name="Germantown" />
        <Area name="Wauwatosa" />
      </Region>
      <Region name="Fox Valley">
        <Area name="Oshkosh" />
        <Area name="Appleton" />
      </Region>
    </Regions>
  </State>
</States>

Enjoy!

Filed under: , , , , , ,

Comments

# Interesting Finds: August 21, 2009

Friday, August 21, 2009 6:57 AM by Jason Haley

Interesting Finds: August 21, 2009

# re: Adding Nodes to an XML String

Friday, August 21, 2009 9:44 AM by Waleed El-Badry

Hello Deobrah,

Don't you agree that importing Schema would simplify the LINQ query to avoid mistyping errors?

Thanks again for your lovely post

# Adding Nodes to an XML String - Deborah Kurata

Sunday, August 23, 2009 2:56 PM by DotNetShoutout

Thank you for submitting this cool story - Trackback from DotNetShoutout

# Writing to an XML File With Attributes

Tuesday, June 08, 2010 12:07 AM by Deborah's Developer MindScape

This prior post demonstrated a very simple technique for writing to an XML file that has a set of elements

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: