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.
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.
If the 2 guid's are the same then this line of code deletes that contact node as a whole.
Again this just saves the current xml file, but this time with the data gone.
Any questions, comments, or suggestions are welcome please leave a comment.