tags:

views:

185

answers:

2

I appreciate that there are now many mechanisms in dotnet to deal with XML in a myriad of ways...

Suppose I have a string containing the XML....

<?xml version="1.0" encoding="utf-8" ?>
<root>
    <Element1>
        <Element1_1>
            SomeData
        </Element1_1>
    </Element1>
    <Element2>
        Some More Data
    </Element2>
</root>

What is the simplest (most readable) way of removing Element1_1?

Update... I can use any .Net API available in .Net 3.5 :D

+6  A: 

Which APIs are you able to use? Can you use .NET 3.5 and LINQ to XML, for instance? If so, XNode.Remove is your friend - just select Element1_1 (in any of the many ways which are easy with LINQ to XML) and call Remove() on it.

Examples of how to select the element:

XElement element = doc.XPathSelectElement("/root/Element1/Element1_1");
element.Remove();

Or:

XElement element = doc.Descendants("Element1_1").Single().Remove();
Jon Skeet
Could you clarify how I might "select Element1_1" simply given a suitable xpath.
Rory Becker
You could use one of the XPaths given in Tomalak's answer, using the XPathSelectElement extension method.
Jon Skeet
Accepted over Tomalak purely because I favour XDoc over XMLDoc syntax. Upvoted both answers.
Rory Becker
+6  A: 

I'd use either this:

XmlDocument x = new XmlDocument();
x.LoadXml(SomeXmlString);

foreach (XmlNode xn in x.SelectNodes("//Element1_1"))
  xn.ParentNode.RemoveChild(xn);

or the same with an explicit XPath:

foreach (XmlNode xn in x.SelectNodes("/root/Element1/Element1_1"))
  xn.ParentNode.RemoveChild(xn);

or, even more specific:

XmlNode xn = x.SelectSingleNode("/root/Element1/Element1_1");
xn.ParentNode.RemoveChild(xn);
Tomalak