How To : Add XML Attribute To An Existing XML Node in C# (C Sharp)

Hey Folks,

I had requirement where I needed to add an XML Attribute to an existing XML Node.

Say for example I have an XML file as below :

XML Code :

<xml>
<User Name="Naimish" Country="India" Mobile="0123456789" UserExits="Yes" />
<User Name="Vishal"  		     Mobile="0123456788" UserExits="Yes" />
<User Name="Lucky"   Country="India" Mobile="0123456787" UserExits="Yes" />
<User Name="Ravi" 		     Mobile="0123456786" UserExits="Yes" />
<User Name="XYZ"     Country="India" Mobile="0123456785" UserExits="Yes" />
</xml>

Now, If you notice, User Vishal and User Ravi don’t have an attribute Country, so If you want to add that attribute pro-grammatically using C# or C Sharp Code, here’s how you go :

C# / C Sharp Code :

      
     class AddAttributesToXML
     {
        static void Main(string[] args)
        {
            if (File.Exists("C:\\Test.xml"))
            {
                XmlDocument XDoc = new XmlDocument();
                XDoc.Load("C:\\Test.xml");
                XDoc.InnerXml = AddAttributesToXML(XDoc.OuterXml);
                XDoc.Save("C:\\Test.xml");
            }
        }

        private static string AddAttributesToXML(String inputXml)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(inputXml);

            XmlNodeList xmlNodeList = xmlDoc.GetElementsByTagName("User");

            foreach (XmlNode xmlNode in xmlNodeList)
            {
                try
                {
                    if (xmlNode.Attributes.GetNamedItem("Country").Value == null) { }
                }
                catch (Exception)
                {
                    XmlAttribute CountryAttr = xmlDoc.CreateAttribute("Country");
                    CountryAttr.Value = "USA";
                    xmlNode.Attributes.Append(CountryAttr);
                }
            }

            return xmlDoc.OuterXml;
        }
    }

Thanks and Have Fun!!!!!

Advertisements

Tags: , , , ,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: