子元素通过VBA继承父属性

时间:2013-12-18 06:41:02

标签: xml vba excel-vba namespaces excel

我正在研究excel 2013的xml输出,我已经设置了对XML v6库的引用,但我没有得到我期望的结果。 这是我正在使用的代码:

Sub testXML()

Dim dom, node, attr, PCMS, SendPCMS, header

Set dom = CreateDom
Set node = dom.createProcessingInstruction("xml", "version='1.0' encoding='utf-8'")
dom.appendChild node
Set node = Nothing

Set PCMS = dom.createElement("PCMS")
Set attr = dom.createAttribute("xmlns")
attr.Value = "MyNamespace"
PCMS.setAttributeNode attr
Set attr = Nothing
dom.appendChild PCMS

Set SendPCMS = dom.createElement("SendPCMSManifest")
PCMS.appendChild SendPCMS
Set header = dom.createElement("header")
PCMS.appendChild header

dom.Save "C:\Temp\DomTest.xml"

End Sub
Private Function CreateDom()
Dim dom
Set dom = New DOMDocument
dom.async = False
dom.validateOnParse = False
dom.resolveExternals = False
dom.preserveWhiteSpace = True
Set CreateDom = dom
End Function

出于某种原因,属性“xmlns”也被应用于子元素(但只有属性名称,而不是值),如下所示:

?xml version="1.0" encoding="UTF-8"?>
PCMS xmlns="MyNamespace">
 SendPCMSManifest xmlns=""/>
 header xmlns=""/>
/PCMS>

有人能告诉我哪里出错了吗?元素“SendPCMSManifest”& “header”不应在节点名称中包含“xmlns =”

编辑:尝试获取示例输出xml显示

1 个答案:

答案 0 :(得分:5)

Sub testXML()

Dim dom, node, PCMS

    Set dom = CreateDom
    Set node = dom.createProcessingInstruction("xml", "version='1.0' encoding='utf-8'")
    dom.appendChild node
    Set node = Nothing

    Set PCMS = dom.createNode(1, "PCMS", "MyNamespace")
    dom.appendChild PCMS

    PCMS.appendChild dom.createNode(1, "SendPCMSManifest", "MyNamespace")
    PCMS.appendChild dom.createNode(1, "header", "MyNamespace")

    Debug.Print dom.XML

End Sub

Private Function CreateDom()
    Dim dom
    Set dom = New DOMDocument
    dom.async = False
    dom.validateOnParse = False
    dom.resolveExternals = False
    dom.preserveWhiteSpace = True
    Set CreateDom = dom
End Function

输出:

<?xml version="1.0"?>
<PCMS xmlns="MyNamespace"><SendPCMSManifest/><header/></PCMS>