如何在 VBA Excel 2003 中解析 XML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6010031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 13:14:40  来源:igfitidea点击:

How to parse XML in VBA Excel 2003?

xmlexcelvba

提问by Bogdan P.

I am trying to parse a general XML file, via VBA. What I want to do with it: extract the values of the xml nodes, write them into a XML file and export it.

我正在尝试通过 VBA 解析一个通用的 XML 文件。我想用它做什么:提取 xml 节点的值,将它们写入 XML 文件并导出。

Do you know any library that actually lets me read one node at a time, for me to process with a understandable documentation, and some examples, even minimal ones.

你知道有什么库可以让我一次读取一个节点,让我用易于理解的文档和一些例子来处理,甚至是最小的例子。

So far:

迄今为止:

Sub Go()

    Dim xmlDoc As MSXML2.DOMDocument
    Dim xmlElement As MSXML2.IXMLDOMElement
    Dim xmlNode As MSXML2.IXMLDOMElement

    Set xmlDoc = New MSXML2.DOMDocument
    xmlDoc.Load ("E:\cdCatalog.xml")

    Set xmlElement = xmlDoc.documentElement
    Set xmlNode = xmlElement.FirstChild

    parseNodes xmlElement, 1, 1
    'parseNodes xmlNode, 1, 1

End Sub

Sub parseNodes(node As MSXML2.IXMLDOMElement, i As Integer, j As Integer)
    Dim child As MSXML2.IXMLDOMNode

    'result = node.baseName & " : " & node.Text
    result = node.nodeName

    Sheet1.Activate
    ' text if...
    Cells(i, j) = result

    j = j + 1
    If (node.hasChildNodes) Then

        For Each child In node.childNodes
            i = i + 1
            'MsgBox child.Text
            MsgBox TypeName(node.childNodes)
            parseNodes child, i, j
        Next
    End If

End Sub

回答by Jean-Fran?ois Corbett

Addressing your updated question as specified in your comment:

解决您在评论中指定的更新问题:

You can't instance objects in VBA like that, with an argument in the Dimstatement. Try:

你不能像那样在 VBA 中实例化对象,在Dim语句中带有一个参数。尝试:

Dim gReader As XmlTextReader
gReader = New XmlTextReader

Also, I suggest you read the XmlTextReaderdocumentation here:

另外,我建议您阅读XmlTextReader此处的文档:

http://msdn.microsoft.com/en-us/library/1af7xa52.aspx

http://msdn.microsoft.com/en-us/library/1af7xa52.aspx

The examples illustrate how to use XmlTextReader.

这些示例说明了如何使用XmlTextReader.

EDIT:As far as I can tell from a cursory internet search, XmlTextReaderis implemented for .NET but not for VBA.

编辑:据我从粗略的互联网搜索中可以看出,XmlTextReader是为 .NET 而不是为 VBA 实现的。

You may want to consider using DOM instead of XmlTextReader. I find DOM relatively easy to use. The downside is that it is inefficient for very large XML files. Unless you are manipulating large files, DOM should work fine for you.

您可能需要考虑使用 DOM 而不是XmlTextReader. 我发现 DOM 比较容易使用。缺点是对于非常大的 XML 文件效率低下。除非您要操作大文件,否则 DOM 应该适合您。

Dim xlmDoc As Object
Set xlmDoc = CreateObject("Msxml2.DOMDocument.6.0")
xmlDoc.Load fileName