Here is an example of adding an attribute to an XmlDocument in C# and .Net. The below code reads in Xml. Where there are nodes that do not contain and ID attribute, we will add that attribute using the name as the value.

 1: public static string xmlAcct =
 2: @"<?xml version='1.0' encoding='utf-8'?>
 3: <Accounts>
 4: <acct acct='aex113' country_code='us' name='abcde' />
 5: <acct acct='aex114' name='eeaad' country_code='us' />
 6: <acct acct='aex115' country_code='us' name='eoo' id='eoo9' />
 7: </Accounts>
 8: ";
 9:
 10: public static void AddAttribute()
 11: {
 12:
 13:     XmlDocument originalXml = new XmlDocument();
 14:
 15:
 16:     originalXml.LoadXml(xmlAcct);
 17:
 18:     XmlNodeList accts
 19:        = originalXml.SelectNodes("descendant::*[name(.) ='acct']");
 20:     XmlNode temp;
 21:     XmlNode name;
 22:     XmlAttribute attr;
 23:
 24:     foreach (XmlNode current in accts)
 25:     {
 26:         temp = current.SelectSingleNode("@id");
 27:         if (temp == null)
 28:         {
 29:             name = current.SelectSingleNode("@name");
 30:             if (name != null)
 31:             {
 32:                 attr = originalXml.CreateAttribute("id");
 33:                 attr.InnerText = name.InnerText;
 34:                 current.Attributes.Append(attr);
 35:             }
 36:         }
 37:
 38:     }
 39:
 40:     Console.WriteLine(originalXml.OuterXml);
 41:
 42:
 43: }
  • Line 01: Create Test XMl
  • Line 16: Load the test Xml.
  • Line 19: Get all the account nodes using Xpath.
  • Line 24: Work through each account node to add an attribute if ID does not exist.
  • Line 27: When null we need to add the ID node.
  • Line 29: We will use the name as the ID.
  • Line 32: We have to create the attribute off of the current node. Very important, for we can’t just slap any old node on. It has to be from the current branch/node.
  • Line 40: Display the changes.
Share