Abid
Abid

Reputation: 13

How to delete specific node by attribute from XML?

I am novice and struggling in some XML operations Like open and Delete. I have done the Add part.

Partys.xml

<?xml version="1.0" encoding="utf-8"?>
<Partys>
  <Customers>
    <Customer CustomerID="1">
      <PersonalName>
        <LastName>Baker</LastName>
        <FirstName>Eugene</FirstName>
      </PersonalName>
      <Citizenship>Africa</Citizenship>
    </Customer>
    <Customer CustomerID="2">
      <PersonalName>
        <LastName>Baker</LastName>
        <FirstName>Eugene</FirstName>
      </PersonalName>
      <Citizenship>Africa</Citizenship>
    </Customer>
  </Customers>
 </Partys>

Q: I want to open the node detail customer where CustomerID (Attribute) is 1. What is the C# code for this?

Q: I want to delete the node customer where CustomerID (Attribute) is 2. What is the C# code for this?

Upvotes: 1

Views: 7877

Answers (1)

Varun Chatterji
Varun Chatterji

Reputation: 5099

You could try something like this:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Parties.xml");
XmlNode t = xmlDoc.SelectSingleNode("/Partys/Customers/Customer[@CustomerID='2']");
t.ParentNode.RemoveChild(t);
xmlDoc.Save();

Once you have t, you can do whatever you want with it including show it in the Console (by accessing the various properties)

Here, we have deleted the node and saved back to file, but you could do whatever you want with the XmlDocument....

Upvotes: 7

Related Questions