I have an XDocument and have to remove a node and add the very same node back again after some manipulation(my xelement node are complex and have inner nodes as well). Has anyone got a good way to do this as my new manipulated node is being added at the very end of the xmldocument. Any code snippets would be greatly appreciated.
+1
A:
If I understand you right, this should help you do it.
SolarSystem.xml:
<?xml version="1.0" encoding="UTF-8"?>
<SolarSystem>
<Planets>
<Planet Id="1">
<Name>Mercury</Name>
</Planet>
<Planet Id="2">
<Name>Venus</Name>
</Planet>
<Planet Id="3">
<Name>Earth</Name>
</Planet>
</Planets>
</SolarSystem>
The code finds the <Planet>
Mercury, adds an extra element to it, removes it, and reinserts it at the end of the <Planets>
collection.
XDocument SolarSystem = XDocument.Load(Server.MapPath("SolarSystem.xml"));
IEnumerable<XElement> Planets = SolarSystem.Element("SolarSystem").Element("Planets").Elements("Planet");
// identify and change Mercury
XElement Mercury = Planets.Where(p => p.Attribute("Id").Value == "1").FirstOrDefault();
Mercury.Add(new XElement("YearLengthInDays", "88"));
// remove Mercury from current position, and add back in at the end
Mercury.Remove();
Planets.Last().AddAfterSelf(Mercury);
// save it as new file
SolarSystem.Save(Server.MapPath("NewSolarSystem.xml"));
which gives:
<?xml version="1.0" encoding="UTF-8"?>
<SolarSystem>
<Planets>
<Planet Id="2">
<Name>Venus</Name>
</Planet>
<Planet Id="3">
<Name>Earth</Name>
</Planet>
<Planet Id="1">
<Name>Mercury</Name>
<YearLengthInDays>88</YearLengthInDays>
</Planet>
</Planets>
</SolarSystem>
Rafe Lavelle
2009-11-04 01:00:19
+1: Nice 101 sample to get people started
Ruben Bartelink
2009-12-10 11:44:06
+2
A:
If you're just editing the node, then why remove it at all? Just get a reference to it in the tree and edit it in-place.
If that's not an option for some reason, then one way to go about it is this: once you've found the XElement
(or, in general, XNode
) you need to replace in the tree, create a new XElement
to serve as a replacement, and then use XNode.ReplaceWith
method on the old element, passing new one as the argument.
Pavel Minaev
2009-11-04 01:19:06