XML 文档必须有一个元素是所有其他元素的父元素。该元素称为根元素。
由于XML 中所有成分都是节点,根元素又可以称为根节点。
可以使用XML DOM 的documentElement 属性访问XML的根节点。
以下代码可以读取任意一个XML文档的根节点的类型,根节点的标签名:
Sub QQ1722187970()
Const NODE_ELEMENT = 1
Const NODE_ATTRIBUTE = 2
Const NODE_TEXT = 3
Const NODE_COMMENT = 8
Const NODE_DOCUMENT = 9
'定义一个变量用于存储文本xml
Dim sXml As String
sXml = "<?xml version=""1.0"" encoding=""utf-8""?>" & _
"<note>" & _
"<to>George</to>" & _
"<from>John</from>" & _
"<heading>Reminder</heading>" & _
"<body>Don't forget the meeting!</body>" & _
"</note>"
'定义一个变量用于存储xml文件
Dim sPathXml As String
sPathXml = Excel.ThisWorkbook.Path & "\test.xml"
'定义一个解析xml的变量对象
Dim oXml As Object
Set oXml = VBA.CreateObject("Msxml2.DOMDocument.6.0")
' Set oXml = VBA.CreateObject("Microsoft.XMLDOM")
With oXml
'不异步导入xml源
.async = False
'导入xml文件
.Load (sPathXml)
'导入xml文本
' .LoadXML (sXml)
With .parseError
If .ErrorCode = 0 Then
Debug.Print "解析成功"
'解析成功
'****************************
'返回xml文档的根节点
Set oRoot = oXml.DocumentElement
With oRoot
Debug.Print .NodeType
Debug.Print .nodeName
Debug.Print .NodeValue
End With
'****************************
Else
'如果解析错误,输出错误的原因
Debug.Print .reason
End If
End With
'定义一个存储最终xml的文件路径
Dim sResultXml As String
sResultXml = Excel.ThisWorkbook.Path & "\result.xml"
'将解析修改后的xml存盘
.Save sResultXml
End With
End Sub


发表评论