Published
Thursday, January 24, 2008 4:08 AM
by
mtaulty
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.