我有一个看起来像这样的 xml 文档:
<rng>
<col1>
<row1>A</row1>
<row2>B</row2>
<row3>C</row3>
<row4>D</row4>
</col1>
<col2>
<row1>E</row1>
<row2>F</row2>
<row3>G</row3>
<row4>H</row4>
</col2>
</rng>
col 节点更多,每个节点包含数千行元素。
我想从行元素中解析出值并最终将它们放到电子表格中。我目前这样做如下:
' get a list of the col elements (thi sits in a loop to go through them all)
Set oXMLColNodeList = oXMLDoc.selectNodes("//saveStates/rng/*")
' Lop through each column
For colNum = 1 To oXMLColNodeList.Length
' get all the row nodes for that coulmn
Set oXMLRowNodeList = oXMLDoc.selectNodes("//saveStates/rng"/col" & colNum & "/*")
' loop through all the row nodes
For rowNum = 1 To oXMLRowNodeList.Length
' get the node to do something with it
Set oXMLNode = oXMLDoc.selectSingleNode("//saveStates/rng/col" & colNum & "/row" & rowNum)
next rowNum
next colNum
IE。我正在遍历 col 节点,然后遍历每个行节点以获取值 A、B、C、D 等。当行元素的数量接近数万时,它的速度非常慢。
我在解析 XML 文档方面没有太多经验,我正在寻找一种方法来同时从“行*”节点中提取所有值,而不必遍历它们。这可能吗?
最佳答案
也许你可以使用 ADO DB 记录集 在 Recordset 中打开 xml DOM 文档,然后使用 Range.CopyFromRecordset 添加过滤器以仅获取所需记录后将数据转储到 Excel 的方法?
这是来自 MSDN: How to obtain a Recordset from XML 的一些示例代码
Public Function RecordsetFromXMLDocument(XMLDOMDocument As DOMDocument) As Recordset
Dim oRecordset As ADODB.Recordset
dim destRange as range
set destrange=range("B2")
Set oRecordset = New ADODB.Recordset
oRecordset.Open XMLDOMDocument 'pass the DOM Document instance as the Source argument
Set RecordsetFromXMLDocument = oRecordset 'return the recordset
destRange.CopyFromRecordset oRecordset
Set oRecordset = Nothing
End Function
关于xml - 将多个xml节点提取到数组中而不循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16212830/