11/15/2011

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!!!!!

0 comments: