Best way to remove an item in a known place from an XML string using DotNet?

I appreciate that dotnet has many mechanisms for working with XML in a variety of ways ...

Suppose I have a string containing 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 easiest (most readable) way to remove Element1_1?

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

+3
source share
2 answers

What APIs can you use? Can you use .NET 3.5 and LINQ to XML, for example? If so, XNode.Remove is your friend - just select Element1_1 (in any of the many ways that make LINQ to XML easier) and call Remove () on it.

Element selection examples:

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

Or:

XElement element = doc.Descendants("Element1_1").Single().Remove();
+7
source

:

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

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

XPath:

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

, :

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

Source: https://habr.com/ru/post/1698513/


All Articles