Working with Attributes
Although attributes belong to a particular element, they are not considered child nodes of element nodes. Instead, they behave more like properties of IXMLDOMElement
.
Most of the methods for working with attributes come from IXMLDOMElement
. Attributes can be manipulated in the following ways.
Directly, through the
getAttribute
andsetAttribute
methods ofIXMLDOMElement
.As named
IXMLDOMAttribute
nodes, withgetAttributeNode
andsetAttributeNode
.As a set of nodes accessible through the
attributes
property and returned as anIXMLNamedNodeMap
.
Examples
JScript
The following JScript example creates a new document containing a <memo>
element, and then creates an attribute named author
with a value of "Pat Coleman"
.
var xmlDoc = new ActiveXObject("Msxml2.DOMDocument.6.0");
var rootElement=xmlDoc.createElement("memo");
rootElement.setAttribute("author", "Pat Coleman");
xmlDoc.appendChild(rootElement);
VBScript
Set xmlDoc = CreateObject
("Msxml2.DOMDocument.6.0")
Set rootElement=xmlDoc.createElement
("memo")
rootElement.setAttribute "author", "Pat Coleman"
xmlDoc.appendChild
(rootElement)
If you prefer to work with attribute nodes, you can create the attribute, and then create a text node to store its value. Attribute nodes can only contain text nodes and entity reference nodes. (If you need to create an attribute containing an entity reference, you must use this approach.)
Working with attribute nodes requires using the DOMDocument
object to create attribute and text (and entity reference, if necessary) nodes before assigning the nodes to the element.
JScript
The following JScript code uses this approach to perform the same work as the preceding examples, creating a <memo>
element with an author
attribute holding the value "Pat Coleman"
.
var xmlDoc = new ActiveXObject("Msxml2.DOMDocument.6.0");
var rootElement=xmlDoc.createElement("memo");
var memoAttribute=xmlDoc.createAttribute("author");
var memoAttributeText=xmlDoc.createTextNode("Pat Coleman");
memoAttribute.appendChild(memoAttributeText);
rootElement.setAttributeNode(memoAttribute);
xmlDoc.appendChild(rootElement);
WScript.Echo(xmlDoc.xml);
VBScript
Set xmlDoc = CreateObject
("Msxml2.DOMDocument.6.0")
Set rootElement=xmlDoc.createElement
("memo")
Set memoAttribute=xmlDoc.createAttribute
("author")
Set memoAttributeText=xmlDoc.createTextNode
("Pat Coleman")
memoAttribute.appendChild
(memoAttributeText)
rootElement.setAttributeNode
(memoAttribute)
xmlDoc.appendChild
(rootElement)
Developers who want to work with attributes as a set can also use the IXMLDOMNamedNodeMap
collection returned by the attribute
property of IXMLDOMElement
.
For more information about properties and methods of IXMLDOMAttribute
, see IXMLDOMAttribute.