mike oconner
mike oconner

Reputation: 69

Remove children nodes in XML using Linq

I have an XML file with a list of parent nodes and childe nodes nested within the parent node, and I need to remove the child nodes when a specific criteria is been met. Ex: Remove all contact nodes where the id = 1. How can I achieve this using linq and xml. This is my XML structure

<Events>
 <Event>
    <id>1</id>
    <title>AA</title>
    <start>2019-12-01T14:13:58.863</start>
    <end>2019-12-01T15:13:58.787</end>
    <contacts>

      <contact>
        <id>1</id>
        <name>ABC</name>
      </contact>

      <contact>
        <id>2</id>
        <name>ABCD</name>
      </contact>

      <contact>
        <id>3</id>
        <name>ABCDE</name>
      </contact>

    </contacts>
 </Event>

<Event>
    <id>2</id>
    <title>BB</title>
    <start>2019-12-01T14:13:58.863</start>
    <end>2019-12-01T15:13:58.787</end>
    <contacts>

      <contact>
        <id>1</id>
        <name>ABC</name>
      </contact>

      <contact>
        <id>2</id>
        <name>ABCD</name>
      </contact>

      <contact>
        <id>3</id>
        <name>ABCDE</name>
      </contact>

    </contacts>
 </Event>
</Events>

Upvotes: 0

Views: 714

Answers (2)

Yitzhak Khabinsky
Yitzhak Khabinsky

Reputation: 22301

As Jon Skeet pointed out there is no need to do anything esoteric. Here is a complete example how to do it. Pure LINQ to XML.

c#, LINQ to XML

void Main()
{
    const string inputXML = @"e:\Temp\MikeOconner.xml";
    const string outputXML = @"e:\Temp\MikeOconner_output.xml";

    XDocument xml = XDocument.Load(inputXML);

    xml.Root.DescendantsAndSelf("contact")
        .Where(r => (string)r.Element("id").Value == "1")
        .Remove();
    xml.Save(outputXML);
}

Upvotes: 1

Rasheen Ruwisha
Rasheen Ruwisha

Reputation: 155

You can get the XML nodes using this query

var query = xmlDoc.Descendants("contact").Where(e => e.Element("id").Value.Equals(id)).ToList();

And then run

query.Remove()

to remove the elements that were returned.

Upvotes: 1

Related Questions