1

I need to add same attribute to different nodes. Is there a way to define the attribute once and use it many times ?

Here is what I tried to do:

Set myAttribute = xmlDoc.createAttribute("operation")
attribute.value = "delete"

Now I can do the following:

node.attributes.setNamedItem(myAttribute)

But if want do add the same attribute to another node, I get an error. Like:

node2.attributes.setNamedItem(myAttribute)

So, is there a way to re-use the attribute without repeating the first two lines of code?

1 Answer 1

1

In your code, myAttribute variable is an object reference so it points to same all the time. You need to clone the node. Have a look at cloneNode Method.

Set xmldoc = CreateObject("msxml2.domdocument")
    xmldoc.loadXML "<root/>"

Set theElement = xmldoc.createElement("element")
Set theAttribute = xmldoc.createAttribute("attribute")
    theAttribute.value = "delete"

For i = 1 To 15
    With xmlDoc.documentElement.appendChild(theElement.cloneNode(True))
        .attributes.setNamedItem(theAttribute.cloneNode(True))
    End With
Next

WScript.Echo xmldoc.xml

output (indented and prettified manually):

<root>
  <element attribute="delete"/>
  <element attribute="delete"/>
  <element attribute="delete"/>
  <element attribute="delete"/>
  <element attribute="delete"/>
  <element attribute="delete"/>
  <element attribute="delete"/>
  <element attribute="delete"/>
  <element attribute="delete"/>
  <element attribute="delete"/>
  <element attribute="delete"/>
  <element attribute="delete"/>
  <element attribute="delete"/>
  <element attribute="delete"/>
  <element attribute="delete"/>
</root>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.