Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel VBA中的XML和XPath处理_Excel_Xml_Vba - Fatal编程技术网

Excel VBA中的XML和XPath处理

Excel VBA中的XML和XPath处理,excel,xml,vba,Excel,Xml,Vba,我正在尝试使用VBA将XML解析为电子表格,但由于某些原因,我无法使用XPath连接到我想要的节点,下面是我的XML的外观: <?xml version="1.0" encoding="UTF-8"?> <cteProc xmlns="http://www.somesite.com" versao="3.00"> <CTe xmlns="http://www.somesite

我正在尝试使用VBA将XML解析为电子表格,但由于某些原因,我无法使用XPath连接到我想要的节点,下面是我的XML的外观:

<?xml version="1.0" encoding="UTF-8"?>
<cteProc xmlns="http://www.somesite.com" versao="3.00">
 <CTe xmlns="http://www.somesite.com">
  <infCte Id="an id" versao="3.00">
    <ide>
     <cUF>23</cUF>
     <cCT>00000557</cCT>
     <CFOP>6932</CFOP>
     <natOp>some text </natOp>
     <mod>57</mod>
    </ide>
    <compl>
      <xObs>TEXT</xObs>
    </compl>
  </infCte>
 </CTe>
</cteProc>
所以我试着打印节点的长度,我得到:

debug.print nodes.length

> 0
> CTe
如果我这样循环:

Public Sub parseXml()

Dim oXMLFile As MSXML2.DOMDocument60
Dim nodes As MSXML2.IXMLDOMNodeList

path2 = "C:\Users\me\Desktop\adoc.xml"

Set oXMLFile = New MSXML2.DOMDocument60

oXMLFile.Load (path2)

Set nodes = oXMLFile.DocumentElement.SelectNodes("/CTe")
Public Sub parseXml()

Dim oXMLFile As MSXML2.DOMDocument60
Dim nodes As MSXML2.IXMLDOMNodeList
Dim node As MSXML2.IXMLDOMNode

path2 = "C:\Users\me\Desktop\adoc.xml"

Set oXMLFile = New MSXML2.DOMDocument60

oXMLFile.Load (path2)


Set nodes = oXMLFile.DocumentElement.ChildNodes


For Each node In nodes
    Debug.Print node.BaseName
Next node
我明白了:

debug.print nodes.length

> 0
> CTe

因此,如果我做一个巨大的循环,我可以得到我想要的信息,但我认为必须有一个更简单的解决方案。

因为您的
XML
使用名称空间,
XPath
也需要处理名称空间

使用您的
XML
,以下内容适用于我:

Public Sub parseXml()

 Dim oXML As MSXML2.DOMDocument60
 Dim oNodes As MSXML2.IXMLDOMNodeList
 Dim oItem As MSXML2.IXMLDOMNode
 Dim path2 As String
 
 path2 = "P:\adoc.xml"

 Set oXML = New MSXML2.DOMDocument60

 oXML.Load path2
 oXML.setProperty "SelectionLanguage", "XPath"
 oXML.setProperty "SelectionNamespaces", "xmlns:ssc=""http://www.somesite.com"""
 
 Set oNodes = oXML.DocumentElement.SelectNodes("ssc:CTe")
 
 For Each oItem In oNodes
  MsgBox oItem.nodeName
 Next

End Sub
有使用

oXMLFile.setProperty "SelectionNamespaces", "xmlns:ssc=""http://www.somesite.com"""
我为名称空间定义了前缀
ssc

http://www.somesite.com

scc
是我自己的选择(somesite.com)。
selectNodes
方法中的
XPATH
需要此前缀才能正常工作

如果不想定义名称空间,则必须使用
local-name()
XPath函数。例如:

Set oNodes = oXML.DocumentElement.SelectNodes("*[local-name() = 'CTe']")

谢谢,成功了。