分析 VBA 数组中的 XML 示例



我正在尝试使用VBA解析XML。XML 具有以下结构:

<?xml version="1.0" encoding="utf-8"?>
<T>
<P>
<D> 
<A> something 1<A> 
<A> something 2<A>
<D>
<P>
<P>
<E>                     
<B> something 3<B> 
<B> something 4<B>
<E>
<P>
<T>
`

我正在尝试编写一段代码,该代码在 P 的第二个节点中循环以获取数组中 B 的值 [某物 3,某物 4]。如果你有一些代码可以"扁平化"数组中的XML,那也很有趣。

要实现您的目标,您可以使用Microsoft XML library.以下是满足您需求的Sub

Sub getNodesValues()
Dim xmlDoc As New DOMDocument30 'Need Reference "Microsoft Xml, 3.0"
xmlDoc.Load ("C:UsersmyusernameDesktoptest.xml") 'Set your file name
xmlDoc.async = False
Dim nodeList As IXMLDOMNodeList
Dim mainNode As IXMLDOMNode
Dim arr() As String 'Array that will store results
Dim index As Long: index = 1
'This uses xPath to access an element
Set nodeList = xmlDoc.SelectNodes("//P/E/B") 
ReDim arr(1 To nodeList.Length)
'For each node in List
For Each mainNode In nodeList
arr(index) = mainNode.Text 'Store value in array
'Show node name and value in immediate console
Debug.Print mainNode.nodeName & ":" & mainNode.Text
index = index + 1
Next mainNode
'Do what you have to do with your array
'[..]
End Sub

需要注意的重要事项

您可以通过以下行加载文件:

xmlDoc.Load ("C:UsersmyusernameDesktoptest.xml") 'Set your file name

通过这一行,您可以告诉库要在.xml文件中搜索什么:

Set nodeList = xmlDoc.SelectNodes("//P/E/B") 

在此示例中,我们搜索P任何位置的标签,其中包含标签E,其中包含标签B。您可以使用任何需要的内容来更改此设置。

我希望这有所帮助。

Usse xml linq :

Imports System.Xml
Imports System.Xml.Linq
Module Module1
Const FILENAME As String = "c:temptest.xml"
Sub Main()
Dim doc As XDocument = XDocument.Load(FILENAME)
Dim xP As List(Of XElement) = doc.Descendants("P").ToList()
Dim results = xP.Elements().SelectMany(Function(x) x.Elements().Select(Function(y) New With {
             .parent = x.Name.LocalName, _
             .child = y.Name.LocalName, _
             .text = CType(y, String)
         })).ToList()
End Sub
End Module

最新更新