如下的XML代码位于xl文件夹的workbook.xml文件中
<?xml version="1.0" encoding="utf-8"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<fileVersion appName="xl" lastEdited="5" lowestEdited="5" rupBuild="9303"/>
<workbookPr defaultThemeVersion="124226"/>
<workbookProtection workbookPassword="CC40" revisionsPassword="CC40" lockStructure="1" lockRevision="1"/>
<bookViews>
<workbookView xWindow="480" yWindow="120" windowWidth="19440" windowHeight="12585"/>
</bookViews>
<sheets>
<sheet name="Sheet1" sheetId="1" r:id="rId1"/>
</sheets>
<calcPr calcId="145621"/>
<customWorkbookViews>
<customWorkbookView name="xyf" guid="{D5638B0B-396C-4CF2-9C8E-4E6C6243762C}" mergeInterval="0" personalView="1" maximized="1" windowWidth="1276" windowHeight="791" activeSheetId="1"/>
</customWorkbookViews>
</workbook>
当用如下的代码进行解析:
Sub QQ1722187970()
sPath = Excel.ThisWorkbook.Path
'定义一个变量用于存储xml文件
Dim sPathXml As String
sPathXml = sPath & "\xl\workbook.xml"
'定义一个解析xml的变量对象
Dim oXml As Object
Set oXml = VBA.CreateObject("Msxml2.DOMDocument.6.0")
With oXml
'不异步导入xml源
.async = False
'导入xml文件
.Load (sPathXml)
'导入xml文本
' .LoadXML (sXml)
With .parseError
If .ErrorCode = 0 Then
Debug.Print "解析成功"
'解析成功
'****************************
'先找到节点
Set oNode = oXml.SelectSingleNode("//workbookProtection")
'删除节点
oNode.ParentNode.RemoveChild oNode
'****************************
Else
'如果解析错误,输出错误的原因
Debug.Print .reason
End If
End With
End With
End Sub
oNode变量始终返回nothing,也就是找不到workbookProtection元素节点,始终解析不正确,出错。
经过仔细地分析,原因出在
Set oXml = VBA.CreateObject("Msxml2.DOMDocument.6.0")
这条语句,由于Msxml2.DOMDocument.6.0 生成的是最新版本的DOMDocument60对象,它解析xml文件时,用的是最新的标准,要求XML元素都必须有开始和结束标签。而上述的XML代码是不规则的XML代码,有些元素只有开始标签,没有结束标签。所以导致解析不出。
为此,可以将DOMDocument对象换成以下两种均可正常解析:
Set oXml = VBA.CreateObject("Msxml2.DOMDocument.3.0")
Set oXml = VBA.CreateObject("Microsoft.XMLDOM")
修改后的代码如下:
Sub QQ1722187970()
Const NODE_ELEMENT = 1
Const NODE_ATTRIBUTE = 2
Const NODE_TEXT = 3
Const NODE_COMMENT = 8
Const NODE_DOCUMENT = 9
sPath = Excel.ThisWorkbook.Path
'定义一个变量用于存储xml文件
Dim sPathXml As String
sPathXml = sPath & "\xl\workbook.xml"
'定义一个解析xml的变量对象
Dim oXml As Object
' Set oXml = VBA.CreateObject("Msxml2.DOMDocument.6.0")
Set oXml = VBA.CreateObject("Msxml2.DOMDocument.3.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 "解析成功"
'解析成功
'****************************
'先找到节点
Set oNode = oXml.SelectSingleNode("//workbookProtection")
'删除节点
oNode.ParentNode.RemoveChild oNode
'****************************
Else
'如果解析错误,输出错误的原因
Debug.Print .reason
End If
End With
End With
End Sub


发表评论