Kgn-web
Kgn-web

Reputation: 7555

How to remove a complete node from XML in C#

I have C# application. Below is my XML

<subscription>
  <subscription_add_ons type="array">
    <subscription_add_on>
      <add_on_code>bike-o-vision</add_on_code>
      <quantity type="integer">1</quantity>
    </subscription_add_on>
    <subscription_add_on>
      <add_on_code>boxx</add_on_code>
      <quantity type="integer">1</quantity>
    </subscription_add_on>
  </subscription_add_ons>
</subscription>

What I need is if I pass string addOnCode = boxx, remove the complete node i.e.,

<subscription_add_on>
  <add_on_code>boxx</add_on_code>
  <quantity type="integer">1</quantity>
</subscription_add_on>

Function

  XDocument xmlDoc = XDocument.Parse(xmlString);

        XElement element = new XElement(
             "subscription_add_on",
             new XElement("add_on_code", "box"),
             new XElement("quantity",
             new XAttribute("type", "integer"),
        1
    )
);

  xmlDoc.Root.Descendants(element.Name).Remove();

But somehow it's not removing as desired.

How can I do this using XDocument ?

Thanks!

Upvotes: 0

Views: 318

Answers (1)

canton7
canton7

Reputation: 42225

You need to identify the elements you want to remove in the original document, and then call .Remove() on those.

Here, we're looking to find all elements inside the document of type "subscription_add_on", and then filtering to the ones which have a child called "add_on_code" which has the value "boxx". We then remove them all.

xmlDoc.Root
    .Descendants("subscription_add_on")
    .Where(x => x.Element("add_on_code").Value == "boxx")
    .Remove();

Note that .Descendents() will search down multiple levels (so it looks inside your "subscription_add_ons" element to find the "subscription_add_on" children), while .Elements() and .Element() only search down a single level.

See the MSDN docs on linq2xml, and in particular Removing Elements, Attributes, and Nodes from an XML Tree .

Upvotes: 2

Related Questions