Published Thursday, January 24, 2008 4:08 AM by mtaulty

Reparenting nodes in LINQ to XML

Someone mailed me the other day with a query as to how they can use LINQ to XML in order to change this XML file;

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <x>
    <a/>
    <b/>
  </x>
  <c/>
  <d/>
</root>

 

into this XML file;

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <a/>
  <b/>
  <c/>
  <d/>
</root>

 

that is - find the node called "x" and remove it whilst reparenting its child nodes to the parent of the node "x".

I ended up with something like;

      XElement doc = XElement.Load("data.xml");
      XElement xEl = doc.Element("x");
      doc.AddFirst(xEl.Descendants());
      xEl.Remove();

which is fine (enough) but there's a part of me that would have liked to be able to collapse this down into less code.

I managed to get it down to;

     XElement doc = XElement.Load("data.xml");
      XElement xEl = doc.Element("x");
      xEl.ReplaceWith(xEl.Descendants());

which felt a bit better and I can't really think of a way to cut it down much more than that.


Filed Under: ,

# Interesting Finds: January 24, 2008 @ Thursday, January 24, 2008 7:16 AM

Jason Haley

# Link Listing - January 24, 2008 @ Thursday, January 24, 2008 10:58 PM

Link Listing - January 24, 2008

Christopher Steen

# Link Listing - January 24, 2008 @ Thursday, January 24, 2008 10:58 PM

Sharepoint  Integrating an Asp.Net Application into our SharePoint Portal [Via: jesse ]  STSDEV - SharePoint...

Christopher Steen