Zabman
Zabman

Reputation: 117

Child elements inheriting parent attribute through VBA

I am working on an xml output from excel 2013, I have set a reference to the XML v6 library but I am not getting the results I expect. This is the code I am using:

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

For some reason, the attribute "xmlns" is also being applied to the child elements (but only the attribute name, not the value) as per below output:

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

Can anybody show me where I am going wrong? The elements "SendPCMSManifest" & "header" should not have the "xmlns=" in the node name

edited: trying to get example output xml showing

Upvotes: 2

Views: 2450

Answers (1)

Tim Williams
Tim Williams

Reputation: 166980

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

Output:

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

Upvotes: 5

Related Questions