You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel VBA读取带命名空间XML文件无法识别节点报错如何解决

问题原因
  • 报错Error opening input file: 'sequence_schema.xml'是因为MSXML2.DOMDocument60默认会尝试加载XML中引用的外部schema做有效性验证,你本地不存在该schema文件导致验证失败。
  • SelectNodes匹配不到节点是因为你的XML根节点声明了默认命名空间xmlns="x-schema:sequence_schema.xml",所有节点默认归属该命名空间,直接写//SEQUENCE的XPath规则不会命中归属命名空间的节点,需要先声明命名空间前缀再查询。
修复后代码
Option Explicit
Public Sub testing()
    Dim xmlDoc As MSXML2.DOMDocument60
    Dim stepNodes As MSXML2.IXMLDOMNodeList
    Dim stepNode As MSXML2.IXMLDOMNode
    Dim paramNodes As MSXML2.IXMLDOMNodeList
    Dim i As Integer
    
    Set xmlDoc = New MSXML2.DOMDocument60
    ' 关闭外部schema验证、关闭异步加载,避免加载报错
    xmlDoc.validateOnParse = False
    xmlDoc.async = False
    xmlDoc.Load "C:\Users\User\Desktop\Test.xml"
    
    ' 声明命名空间前缀,自定义前缀ns对应XML里的默认命名空间地址
    xmlDoc.setProperty "SelectionNamespaces", "xmlns:ns='x-schema:sequence_schema.xml'"
    
    ' XPath查询时加上命名空间前缀匹配节点
    Set stepNodes = xmlDoc.SelectNodes("//ns:STEPS/ns:STEP")
    
    For Each stepNode In stepNodes
        ' 提取STEP节点的所需属性
        Debug.Print "Recipe: " & stepNode.Attributes.getNamedItem("Recipe").Text
        Debug.Print "Chambers: " & stepNode.Attributes.getNamedItem("Chambers").Text
        ' 提取当前STEP下的CUSTOM_PARAM的Value属性
        Set paramNodes = stepNode.SelectNodes("ns:CUSTOM/ns:CUSTOM_PARAM")
        For i = 0 To paramNodes.Length - 1
            Debug.Print paramNodes(i).Attributes.getNamedItem("Name").Text & ": " & paramNodes(i).Attributes.getNamedItem("Value").Text
        Next i
        Debug.Print "----------------------"
    Next stepNode
End Sub
运行结果

代码执行后,VBA立即窗口会输出你需要的所有值:

Recipe: STANDARD\205C
Chambers: B2B35
Type: PAAP
Block: B2
----------------------
Recipe: STANDARD\110C
Chambers: B2B14
Type: PAHP
Block: B2
----------------------

内容的提问来源于stack exchange,提问作者Wesley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 01:24:00