Mike Taulty's Blog
Bits and Bytes from Microsoft UK
Reparenting nodes in LINQ to XML
Mike Taulty's Blog

Mike's Badges

Follow on Twitter
View mike's profile on slideshare
Add to Technorati Favorites
CW Blog Awards

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.


Posted Thu, Jan 24 2008 4:08 AM by mtaulty
Filed under: ,

Comments

Jason Haley wrote Interesting Finds: January 24, 2008
on Thu, Jan 24 2008 7:16 AM
Christopher Steen wrote Link Listing - January 24, 2008
on Thu, Jan 24 2008 10:58 PM
Link Listing - January 24, 2008
Christopher Steen wrote Link Listing - January 24, 2008
on Thu, Jan 24 2008 10:58 PM
Sharepoint  Integrating an Asp.Net Application into our SharePoint Portal [Via: jesse ]  STSDEV - SharePoint...
(C) Mike Taulty, 2009. All rights reserved. The information in this weblog is provided "AS IS" with no warranties, and confers no rights. This weblog does not represent the thoughts, intentions, plans or strategies of my employer. It is solely my opinion. Inappropriate comments will be deleted at the authors discretion. All code samples are provided "AS IS" without warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability and/or fitness for a particular purpose.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems