Click here to Skip to main content
Click here to Skip to main content

Open, Modify and Save an XML

By , 1 Dec 2011
 

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; 	//Flag to check if changes were made 
				//and we need to save them
            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"))  //Change Customer with your ChildNode Name
                        {
                            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)
            {
                // Your error handling logicgoes here.
            }
}

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!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

nereo.lopez
Software Developer (Senior)
Spain Spain
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 1 Dec 2011
Article Copyright 2011 by nereo.lopez
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid