CodeProject
Welcome back to my blog!
Introduction
This time I will be sharing something simple, that sometimes is needed and usually everybody tends to take more steps than needed.
We will be opening an XML file, modifying it and saving the changes. Let's assume the following scenario to understand the example (I know it is a dummy scenario that won't probably happen, but it is enough to get the point):
We have an XML file with Customers. Every child node will have a single customer with its information in its attributes. Let's imagine that the attributes we have are Id, Name and Email. We will update the email address for a given customer.
The Code
private void ChangeCustomerEmailAddress(stringfilename,
int customerId, string newEmailAddress){
boolchangeMade = false; var xmlFile = new XmlDocument();
try
{
xmlFile.Load(filename);
XmlNode rootXmlNode =xmlFile.DocumentElement;
if (rootXmlNode != null)
{
foreach (XmlNode childNodein rootXmlNode)
{
if(string.Equals(childNode.Name,
"Customer")) {
foreach(XmlAttribute attribute in childNode.Attributes)
{
int currentCustomerId = 0;
if(string.Equals(attribute.Name, "Id"))
{
currentCustomerId = attribute.Value;
}
if(string.Equals(attribute.Name, "Email") &&
currentCustomerId == customerId )
{
attribute.Value = newEmailAddress;
changeMade = true;
break;
}
}
}
}
}
if (changeMade)
{
xmlFile.Save(filename);
}
}
catch (XmlException ex)
{
}
}
Understanding the Code
We have a method that receives the whole path to the XML file we want to modify, the customer ID and the new email address.
We create a new instance of the XmlDocument class and load the document into memory. We loop through the nodes and look into the attributes. When we find the Id attribute, we save its value into a variable (currentCustomerId), so when we reach the Email attribute, if the current customer is the one we want to modify, then we set the current attribute(Email)'s value with the new email address and we exit the loop.
Final Words
It is that simple to modify an XML on the fly in just one step. I hope it helps. Please note this is only a sample code. Feel free to leave any comments, questions, suggestions or whatever your concern is.
Once again, thanks for reading!