Tom Cruise
Tom Cruise

Reputation: 1415

Remove xml node -Xelement

I have a xml file from which only specific nodes have to be removed. The node name will be given as input from the user. How to remove the specific nodes which have requested from the user?

<Customers>    
  <Customer>    
    <id>michle</id>
    <address>newjersy</address>    
  </Customer>    
  <Customer>    
    <id>ann</id>
    <address>canada</address>    
  </Customer>
</Customers>

I have tried

var customer = new XElement("customer",
      from o in customers
      select 
          new XElement("id", id),
          new XElement("address", address)
        );

Customer will contain a new node

<Customer>    
  <id>ann</id>
  <address>canada</address>    
</Customer>

doc.Element("customers").Elements(customer).ToList().Remove();

but this is not working. How can I remove the element from the xml?

Upvotes: 4

Views: 4907

Answers (3)

Vadim Martynov
Vadim Martynov

Reputation: 8892

Your main mistake is that you are creating new nodes that not attached with the source document instead of retrieving existed nodes from it.

You can use article "Removing Elements, Attributes, and Nodes from an XML Tree" on MSDN as a guideline to manipulating XML data.

For example, use XNode.Remove() method to delete one node from the tree or Extensions.Remove<T>(this IEnumerable<T> source) where T : XNode to remove every node in the source collection of nodes:

doc.Descendants("Customer")
    .Where(x => x.Element("id").Value == id)
    .Remove();

But you also need to save document via Save method after that for commit your changes:

doc.Save();

Upvotes: 1

M. Adeel Khalid
M. Adeel Khalid

Reputation: 1796

You can remove this way based on id

        xdoc.Descendants("Customer")
        .Where(x => (string)x.Element("id") == "michle")
        .Remove();

Upvotes: 0

A3006
A3006

Reputation: 1069

Tom,

Try this...

private static void RemoveNode(string sID)
    {
        XDocument doc = XDocument.Load(@"D:\\Projects\\RemoveNode.xml");

        var v = from n in doc.Descendants("Customer")
                     where n.Element("id").Value == sID
                     select n;
        v.Remove();
        doc.Save(@"D:\\Projects\\RemoveNode.xml");
    }

This removed one node when I called it using

RemoveNode("michle");

Hope this helps.

Upvotes: 2

Related Questions