1

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?

5
  • What is an "Open" operation? Like in a visual tree view, expanding the child nodes?!? Commented Aug 23, 2011 at 19:34
  • You might find this link useful: support.microsoft.com/kb/308333 Commented Aug 23, 2011 at 19:36
  • Sorry for being Vague. By Open I tried to indicate show that node detail in the console. Thanks. Commented Aug 23, 2011 at 19:37
  • BTW, there is no such thing as "C#.NET". The language is named "C#". Commented Aug 23, 2011 at 19:55
  • Thank you, John - for the correction. Commented Aug 24, 2011 at 18:22

1 Answer 1

7

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....

Sign up to request clarification or add additional context in comments.

2 Comments

Once more, what is the right way to pass a parameter in SelectSinglenode? int ID; XmlNode t = xmlDoc.SelectSingleNode("/Partys/Customers/Customer[@CustomerID='2']"); How can I send the 'ID' in place of '2'? Thanks Again.
int ID = 2; XmlNode customersNode = xDoc.SelectSingleNode("//Partys/Customers/Customer[@CustomerID=' " + ID + " ' ]"); customersNode.ParentNode.RemoveChild(customersNode); xDoc.Save(@"..\\Partys.xml"); it is showing : Object reference not set to an instance of an object. any clue?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.