我有一個需要用 EXCEL VBA 讀取的 XML 檔案。我正在使用 ChildNodes 搜索 XML 檔案以在子節點中查找值。例如,當我嘗試閱讀時遇到的問題
<strReport><NewDataSet> ,
它不顯示其他 ChildNodes
< BookData>
等等,它只顯示整個文本。
我的理解是這個。
<strReport><NewDataSet>
視為文本。所以,我的問題是如何搜索以找到其中的子節點。
謝謝,
<Project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Products>
<Product>
<ExtensionData />
<Authors>
<Author>
<ID>20260166</ID>
<Name>6</Name>
<X>-7.25</X>
<y>-7.25</y>
</Author>
</Authors>
<Books>
<Book>
<ExtensionData />
<ID>65130346</ID>
<strReport><NewDataSet>
<BookData>
<BookType>top</BookType>
<BookX>0.00</BookX>
<BookY>22.00</BookY>
<BookWidth>16.94</BookWidth>
<BookHeight>22.00</BookHeight>
<BookThick>5.50</BookThick>
</BookData>
<Price>
<PriceType>surface Price</PriceType>
<XDim>0.00</XDim>
<YDim>22.00</YDim>
<Width>16.94</Width>
<Ecc />
<Sales>W 20.00 E 41.25 psf</Sales>
</Price>
</NewDataSet></strReport>
</Book>
</Books>
</Product>
</Products>
</Project>
這是我正在使用的 VBA 代碼
Set XMLDOC = New MSXML2.DOMDocument60
'Load & Wait till complete XML Data is loaded
XMLDOC.async = False
XMLDOC.validateOnParse = False
XMLDOC.Load (xmlFileName)
'XML Loaded. Now Read Elements One by One into XML DOM Objects
Set xmlRoot = XMLDOC.DocumentElement
Set xmlNodes = xmlRoot.FirstChild
For Each xmlNodes In xmlRoot.ChildNodes
If InStr(xmlNodes.XML, "<Products>") <> 0 Then
For Each xmlNodesNext In xmlNodes.ChildNodes
If InStr(xmlNodesNext.XML, "<Product>") = 1 Then
For Each xmlNodesNextNext In xmlNodesNext.ChildNodes
the rest of the code
uj5u.com熱心網友回復:
這是您需要做的事情型別的示例:
Sub Tester()
Dim doc As MSXML2.DOMDocument60, els As Object, el As Object
Dim docReport As MSXML2.DOMDocument60
Set doc = New MSXML2.DOMDocument60
doc.LoadXML ActiveSheet.Range("A1").Text 'loading from a worksheet for testing
'select the nodes with the XML content to be extracted
Set els = doc.SelectNodes("//Project/Products/Product/Books/Book/strReport")
Debug.Print els.Length '>> 1
For Each el In els
Set docReport = New MSXML2.DOMDocument60
docReport.LoadXML el.nodeTypedValue 'load the XML from `strReport`
Debug.Print docReport.SelectSingleNode("//NewDataSet/BookData/BookWidth").nodeTypedValue
Debug.Print docReport.SelectSingleNode("//NewDataSet/Price/Sales").nodeTypedValue
Next el
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/525004.html
標籤:xmlvba
