So here\'s my case.
I have an XElement, let\'s call it root, which has descendents, which have descendents, etc. I pull a descendent using LINQ to XML, load it into
You could use the XNode.ReplaceWith method:
// input would be your edited XML, this is just sample data to illustrate
string input = @"<Artist Name=""Pink Floyd"">
<BandMembers>
<Member>Nick Mason</Member>
<Member>Syd Barret</Member>
<Member>David Gilmour</Member>
<Member>Roger Waters</Member>
<Member>Richard Wright</Member>
</BandMembers>
<Category>Favorite band of all time</Category>
</Artist>";
var replacement = XElement.Parse(input);
var pinkFloyd = xml.Elements("Genre")
.Where(e => e.Attribute("Name").Value == "Rock")
.Elements("Artist")
.Single(e => e.Attribute("Name").Value == "Pink Floyd");
pinkFloyd.ReplaceWith(replacement);
Console.WriteLine(xml);
You should add some error checking though. I used Single
since I'm sure the node exists, but if there's a chance it isn't you should use SingleOrDefault
and check for null
before using the result.
Also, if the input is invalid you'll need to wrap the above code in a try/catch and handle any XmlException
that might be thrown.