Adding new attribute to XML file in C#

SheoNarayan
Posted by SheoNarayan under C# category on | Views : 22289
To add new attribute to XML file, use following code snippets.

private void AppendAttribute()
{
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists("myfile.xml"))
{
xmlDoc.Load("myxml.xml");
XmlNodeList list = xmlDoc.GetElementsByTagName("rect");
int i = 0;
foreach (XmlNode node in list)
{
i++;
// if element already there, it will override
XmlAttribute newAttr = xmlDoc.CreateAttribute("z");
newAttr.Value = i.ToString();
node.Attributes.Append(newAttr);
}

xmlDoc.Save(xmlFile);
}
}


Here, I am trying to add z attribute in every rect node of the existing xml file.

Comments or Responses

Login to post response