读取xml文件结点属性
Sub 读取属性()
'前期绑定
Dim xDox As New DOMDocument60 '定义文档类型
'后期绑定
'Dim xDox As Object
'Set xDox = CreateObject("MSXML2.DOMDocument")
Dim Root As IXMLDOMElement
If (xDox.Load(ThisWorkbook.Path & "\xml属性.xml")) Then
Set Root = xDox.DocumentElement '获取根节点
' MsgBox Root.nodeName ''获取根节点名字
'MsgBox Root.ChildNodes(i).Attributes '子节点的属性, Root.ChildNodes(i).Attributes.Length ,属性个数
' Root.ChildNodes(i).Attributes(0).nodeName '属性0的名称
'MsgBox Root.ChildNodes(i).Attributes(0).Text '属性0的内容
Dim i, j As Integer
'获取标题
With Root.ChildNodes(0)
For i = 0 To .Attributes.Length - 1
' MsgBox .ChildNodes(i).nodeName '获取子节点的子节点的名字
Cells(1, i + 1).Value = .Attributes(i).nodeName ' 把值存入单元格
Next i
End With
For i = 0 To Root.ChildNodes.Length - 1
With Root.ChildNodes(i)
For j = 0 To .Attributes.Length - 1
Cells(i + 2, j + 1).Value = .Attributes(j).Text ' 把值存入单元格
Next j
End With
Next i
End If
End Sub
读取xml文件结点
Sub 读取节点()
'前期绑定
Dim xDox As New DOMDocument60 '定义文档类型
'后期绑定
'Dim xDox As Object
'Set xDox = CreateObject("MSXML2.DOMDocument")
Dim Root As IXMLDOMElement
If (xDox.Load(ThisWorkbook.Path & "\xml节点.xml")) Then '加载文件
Set Root = xDox.DocumentElement '获取根节点
' MsgBox Root.nodeName '获取根节点名字
'MsgBox Root.ChildNodes.Length '子节点个数
'MsgBox Root.ChildNodes(0).nodeName '根节点的第一个子节点的名字
'MsgBox Root.ChildNodes(0).ChildNodes(0).nodeName '根节点的第一个子节点的 子节点的名字
' MsgBox Root.ChildNodes(0).ChildNodes(0).Text '根节点的第一个子节点的 子节点的内容
Dim i, j As Integer
With Root.ChildNodes(0)
For i = 0 To .ChildNodes.Length - 1
' MsgBox .ChildNodes(i).nodeName '获取子节点的子节点的名字
Cells(1, i + 1).Value = .ChildNodes(i).nodeName ' 把值存入单元格
Next i
End With
For i = 0 To Root.ChildNodes.Length - 1 '获取子节点的个数,将子节点的内容输出到单元格
With Root.ChildNodes(i)
For j = 0 To .ChildNodes.Length - 1
Cells(i + 2, j + 1) = .ChildNodes(j).Text
Next
End With
Next i
End If
End Sub