提问人:Munki Fisht 提问时间:7/15/2023 最后编辑:Munki Fisht 更新时间:7/15/2023 访问量:22
尝试查找 XML 标记,但 getElementsByTagName 返回 0 长度
Trying to find XML tags but getElementsByTagName returning 0 length
问:
我正在尝试通过VBA编辑一些XML并使用getElementsByTagName方法查找标签,但它没有返回任何内容。XML文件如下
<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>
代码如下
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
调试输出为
<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
其他标签也不起作用。
答:
1赞
Munki Fisht
7/15/2023
#1
不太确定我是否知道原因,但问题似乎与命名空间一起使用。我遵循了这个例子getElementsByTagName
XML 响应文本的 GetElementsByTagName 不起作用
而不是使用 , 使用 .然后代码如下:getElementsByTagName
SelectNodes
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
输出为
<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
不出所料
评论
getElementsByTagName
SelectNodes
SelectNodes