gpt4 book ai didi

xml - 如何处理excel宏中缺少的xml节点

转载 作者:行者123 更新时间:2023-12-04 20:36:58 25 4
gpt4 key购买 nike

我正在将 ms excel 用于用 vb 编写的宏。我正在读取 xml 文件,循环遍历并且缺少几个节点。请参阅下面的 xml 示例:

<document>
<element>
<fname></fname>
<age></age>
</element>
<element>
<fname></fname>
</element>
</document>

出于某种原因,如果年龄 = 无,则无法正常工作。我在设置年龄线上收到“对象不支持属性或方法”。请参阅下面的宏代码示例。
Sub TestXML()
Dim mainWorkBook As Workbook
Set mainWorkBook = ActiveWorkbook

mainWorkBook.Sheets("Sheet1").Range("A:E").Clear

Dim XDoc As Object
Set XDoc = CreateObject("MSXML2.DOMDocument")

XDoc.async = False
XDoc.validateOnParse = False
XDoc.Load ("C:\MyUnzipFolder\XML_test.XML")

Set fname= XDoc.SelectNodes("/Document/element/fname/text()")
Set age = XDoc.SelectNodes("/Document/element/age/")

If age Is Nothing Then
MsgBox ("element not found.")
Else
MsgBox ("element found.")
End If

Set XDoc = Nothing
End Sub

最佳答案

所有以“element/age”结尾并以“document”开头的路径:

Dim ages As IXMLDOMSelection
Set ages = XDoc.SelectNodes("/document//element/age")

阅读您的评论后:
' Add reference to Microsoft XML, v6.0

Sub TestXML()

Dim XDoc As MSXML2.DOMDocument
Set XDoc = New MSXML2.DOMDocument

XDoc.async = False
XDoc.validateOnParse = True

If Not XDoc.Load("c:\MyUnzipFolder\XML_test.XML") Then
MsgBox XDoc.parseError.reason, vbOKOnly, "Error " & XDoc.parseError.ErrorCode
Exit Sub
End If

' all paths that end in element
Dim elements As IXMLDOMSelection
Set elements = XDoc.SelectNodes("//element")

Dim element As IXMLDOMElement
Dim age As IXMLDOMElement

' loop through each element and try getting its age
Dim r As Long
For Each element In elements
r = r + 1
Set age = element.SelectSingleNode("age")
If Not age Is Nothing Then
' element has age sub element, print its text
ActiveSheet.Cells(r, 1).Value = age.Text
Else
' if nothing then keep cell blank
ActiveSheet.Cells(r, 1).Value = "blank"
End If
Next element

Set XDoc = Nothing
End Sub

XML_test.XML


<?xml version="1.0" encoding="utf-8"?>
<document>
<element>
<fname></fname>
<age>10</age>
</element>
<element>
<fname></fname>
</element>
<element>
<age>40</age>
<fname></fname>
</element>
<element>
<fname></fname>
<age>20</age>
</element>
<element>
<fname></fname>
</element>
<element>
<fname></fname>
</element>
<element>
<fname></fname>
</element>
<element>
<fname></fname>
<age>30</age>
</element>
<element>
<fname></fname>
</element>
</document>

Result



enter image description here

关于xml - 如何处理excel宏中缺少的xml节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40842379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com