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