如何在excel宏中处理丢失的xml节点

时间:2016-11-28 10:46:09

标签: xml excel vba macros

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

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

出于某种原因如果年龄= Nothing那么就不起作用了。我在Set age line上得到“Object不支持属性或方法”。请参阅下面的宏代码示例。

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

1 个答案:

答案 0 :(得分:1)

所有以“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>
  

结果

enter image description here