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 :

<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" />

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.InnerXml = AddAttributesToXML(XDoc.OuterXml);

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

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

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

            return xmlDoc.OuterXml;

Thanks and Have Fun!!!!!


Tags: , , , ,

Leave a Reply

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

You are commenting using your 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: