XML DOM » Element » setAttributeNode

Syntax:
element.setAttributeNode(name)

This method adds the specified new attribute to the element, replacing any pre-existing one of the same name.

Examples

Code:
XML:

<Albums>
   <Album ref="CD142" category="Folk">
      <title>Boil The Breakfast Early</title>
      <artist>The Chieftains</artist>
   </Album>
   <Album ref="CD720" category="Pop">
      <title>Come On Over</title>
      <artist>Shania Twain</artist>
   </Album>
   <Album ref="CD024" category="Country">
      <title>Red Dirt Girl</title>
      <artist>Emmylou Harris</artist>
   </Album>
</Albums>

VBScript:

Set objXMLDoc = CreateObject("Microsoft.XMLDOM")
objXMLDoc.async = False
objXMLDoc.load("albums.xml")

Set Attr = objXMLDoc.createAttribute("category")
Set Text = objXMLDoc.createTextNode("Irish")
Attr.appendChild(Text)

Set Elem = objXMLDoc.documentElement.firstChild
Elem.setAttributeNode(Attr)

Set NamedNodeMap = Elem.attributes
For Each Attr In NamedNodeMap
   document.write(Attr.name + ": " + Attr.value & "<br>")
Next
Output:
ref: CD142
category: Irish
Explanation:

In this example we create a new 'category' attribute and assign it the value 'Irish' by appending a Text node to it. We then use the setAttributeNode method to set it into the first 'Album' element of the 'albums.xml' file. Finally we display all the element's attributes.

Language(s): VBScript XML