I am trying to edit some XML via VBA and find tags using the getElementsByTagName method but it is not returning anything. The XML File is as follows
<ribbon>
<tabs>
<tab label="Lab" id="ID1" insertAfterMso="TabHome">
<group id="Grp1" label="Group 1">
<button id="Button" imageMso="FunctionsInformationInsertGallery" size="large" label="Button"/>
</group>
<group id="Grp2" label="Group 2">
</group>
</tab>
</tabs>
</ribbon>
</customUI>
The code is as follows
Sub ModXML()
Dim rXML As String
Dim respXML As New MSXML2.DOMDocument60
Dim lst As MSXML2.IXMLDOMNodeList
rXML = ThisWorkbook.path & "\ex\example.xml"
Set respXML = New DOMDocument60
respXML.Load (rXML)
Set lst = respXML.getElementsByTagName("tab")
Debug.Print respXML.XML
Debug.Print lst.Length
End Sub
And the debug output is
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="OnLoad">
<ribbon>
<tabs>
<tab label="Lab" id="ID1" insertAfterMso="TabHome">
<group id="Grp1" label="Group 1">
<button id="Button" imageMso="FunctionsInformationInsertGallery" size="large" label="Button"/>
</group>
<group id="Grp2" label="Group 2">
</group>
</tab>
</tabs>
</ribbon>
</customUI>
0
No other tags work either.
Not quite sure I know the reason why, but the issue seems to be using getElementsByTagName
with the namespace. I followed this example
getelementsbytagname for xml response text not working
and rather than using getElementsByTagName
, used SelectNodes
. The code then is as follows:
Sub ModXML()
Dim rXML As String
Dim respXML As New MSXML2.DOMDocument60
Dim lst As MSXML2.IXMLDOMNodeList
Dim nSpace As String
nSpace = "xmlns:doc='http://schemas.microsoft.com/office/2009/07/customui'"
rXML = ThisWorkbook.path & "\ex\example.xml"
Set respXML = New DOMDocument60
respXML.Load (rXML)
respXML.SetProperty "SelectionNamespaces", nSpace
Set lst = respXML.DocumentElement.SelectNodes("//doc:tab")
Debug.Print respXML.XML
Debug.Print lst.Length
End Sub
and the output is
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="OnLoad">
<ribbon>
<tabs>
<tab label="Lab" id="ID1" insertAfterMso="TabHome">
<group id="Grp1" label="Group 1">
<button id="Button" imageMso="FunctionsInformationInsertGallery" size="large" label="Button"/>
</group>
<group id="Grp2" label="Group 2">
</group>
</tab>
</tabs>
</ribbon>
</customUI>
1
as expected