Home » excel » creating xml attributes from Excel VBA

creating xml attributes from Excel VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’ trying to write an xml file from Excel VBA using Microsoft XML 6.0.
So far it works fine, except for some attributes.
This is an excerpt from my code:

Dim block,knoten,subknoten, subknoten2 As MSXML2.IXMLDOMNode
Dim attribut, attribut2 As MSXML2.IXMLDOMAttribute

'...'
Set knoten = block.appendChild(.createNode(NODE_ELEMENT, "name", ""))
Set attribut = .createAttribute("id")
attribut.nodeValue = "Knotentext"
knoten.setAttributeNode attribut ' works fine so far '

Set subknoten = knoten.appendChild(.createNode(NODE_ELEMENT, "unterknoten", ""))
Set subknoten2 = subknoten.appendChild(.createNode(NODE_ELEMENT, "unterknoten2", ""))
subknoten2.nodeTypedValue = "Knotentext"
Set attribut = .createAttribute("id")
attribut.Value ="Attributstext"
subknoten2.setAttributeNode attribut  ' this line creates an error, rest is ok
'...'

The last line leads to the Compiler message “Method or object not found”
This fits with the fact that “setAttributeNode” is not in the selection list when entering subknoten2.
But what’s the difference to knoten? They have both been defined and created the same way.
In the monitoring window (Überwachungsfenster) I see the following types:
knoten: Variant/Object/IXMLDOMElement
subknoten2: IXMLDOMNODE/IXMLDOMElement

Does anyone have an idea what’s going on here and how I can attach an attribute to subknoten2?
Thanks for your time…

How to&Answers:

the problem may be in the DIM declarations:
when you dim without a as clause the variable is declared as a variant

Dim block,knoten,subknoten, subknoten2 As MSXML2.IXMLDOMNode
Dim attribut, attribut2 As MSXML2.IXMLDOMAttribute

block,knoten,subknoten,attribut are all variants

This explains the difference you see in the monitor window, but won’t solve the underlying problem.

The reason you get an error is that setAttributeNode is a method of IXMLDOMElement, not IXMLDOMNode

Hard to be sure form the snippet posted, but it may be you need to use .createElement rather than .createNode

Answer:

You can add attributes to an existing node using the following code

Dim pairList As IXMLDOMNodeList
Dim pairNode As IXMLDOMNode
Dim objAttr As IXMLDOMAttribute

Set pairList = objDom.selectNodes("/PairList/*")



For Each pairNode In pairList
           '--------------------------------------------------
           ' Setting Target Positions
           '-------------------------------------------------
            Set objAttr = objDom.createAttribute("TX")
            pairNode.Attributes.setNamedItem(objAttr).Text = tPoint.X
           Set objAttr = objDom.createAttribute("TY")
            pairNode.Attributes.setNamedItem(objAttr).Text = tPoint.Y
           Set objAttr = objDom.createAttribute("TZ")
            pairNode.Attributes.setNamedItem(objAttr).Text = tPoint.Z


Next pairNode