Part 1: Write to XML File Using C#
Part 2: Reading Data from XML File Using C#
Part 3: Delete Data from XML File Using C#
In the last post on XML, Reading Data from XML File Using C#, we retrieved our data. The only thing we really have left to do is delete data.
I am going to leave updateing data to you to figure out. With these 3 main posts it should be enough for you to figure out how to update data. If not please feel free to leave a comment and I will go ahead and make a post on it, eventually.
The Code
How about we step through this short amount of code. Please, if you haven't taken a look at the other two posts I stongly advise you to.
public void DeleteContact(string theGuid)
In Write to XML File Using C# we mentioned the Guid was going to be used to find unique data to delete out of the xml file, similar to a database. Here we are taking the guid as a sting parameter to compare to all the others guids that we get from our xml file.
XmlNode rootContacts = doc.SelectSingleNode("//contacts");
XmlNodeList nodes = rootContacts.SelectNodes("contact");
Briefly, this gets the main contacts node and takes all the main nodes under that and adds them to a list that we can iterate through. This is explained more in: Reading Data from XML File Using C#.
for(int i = 0; i < nodes.Count; i++)
We are setting up a basic for loop to iterate through our list. We are using a for loop because we can't delete anything out of a list while using a foreach. We start at 0 since most collects start at a base of 0. We are using i < nodes.Count because the "Count" is the total number of objects in the collection and starts at 1 so we don't want to include it with <=.
if(nodes[i].SelectSingleNode("Guid").InnerText == theGuid)
This code is comparing the text of the node Guid inside of the contact node to our parameter we passed to the method.
rootContacts.RemoveChild(nodes[i]);
If the 2 guid's are the same then this line of code deletes that contact node as a whole.
doc.Save(_path);
Again this just saves the current xml file, but this time with the data gone.
Wrap-Up
This was a quick post on how to delete data. If you have followed along with Part 1 and Part 2 then this should be pretty simple. If you haven't looked at them please do.
Any questions, comments, or suggestions are welcome please leave a comment.
XmlAccess.zip (2.22 kb)