Reputation: 86
I would like to generate the following XML from VBA.
<TokenRequest xmlns:common="http://whatever/common" xmlns="http://whatever/api">
<common:header>
<common:requestId>12345</common:requestId>
</common:header>
<software>
<requestId>ABCDE</requestId>
</software>
</TokenRequest>
The issue with my below code is that it generates the xmlns:common attribute also in the common:header node.
So instead of this:
<common:header>
I get this:
<common:header xmlns:common="http://whatever/api">
And this is the piece of code I'm using:
ns1 = "http://whatever/api"
ns2 = "http://whatever/common"
Set xRequest = New DOMDocument
Set xeTokenRequest = xRequest.createNode(NODE_ELEMENT, "TokenRequest", ns1)
xRequest.appendChild xeTokenRequest
Set xeAttrTmp = xRequest.createAttribute("xmlns")
xeAttrTmp.nodeValue = ns1
xeTokenRequest.Attributes.setNamedItem xeAttrTmp
Set xeAttrTmp = xRequest.createAttribute("xmlns:common")
xeAttrTmp.nodeValue = ns2
xeTokenRequest.Attributes.setNamedItem xeAttrTmp
'Create elements
Set xeHeader = xRequest.createNode(NODE_ELEMENT, "common:header", ns1)
xeTokenRequest.appendChild xeHeader
Set xeTmp = xRequest.createNode(NODE_ELEMENT, "common:requestId", ns1)
xeTmp.nodeTypedValue = "12345"
xeHeader.appendChild xeTmp
Set xeSoftware = xRequest.createNode(NODE_ELEMENT, "software", ns1)
xeTokenRequest.appendChild xeSoftware
Set xeTmp = xRequest.createNode(NODE_ELEMENT, "requestId", ns1)
xeTmp.nodeTypedValue = "ABCDE"
xeSoftware.appendChild xeTmp
The full XML generated using above code is the following:
<TokenRequest xmlns:common="http://whatever/common" xmlns="http://whatever/api">
<common:header xmlns:common="http://whatever/api">
<common:requestId>12345</common:requestId>
</common:header>
<software>
<requestId>ABCDE</requestId>
</software>
</TokenRequest>
How can I get rid of that attribute on the node level?
Upvotes: 1
Views: 38
Reputation: 107767
Simply, have prefixed nodes point to its corresponding namespace ("http://whatever/common"
) and without prefix nodes point to default namespaces ("http://whatever/api"
). Recall, a declared namespace prefix overwrites default namespace.
Set xeHeader = xRequest.createNode(NODE_ELEMENT, "common:header", ns2)
Set xeTmp = xRequest.createNode(NODE_ELEMENT, "common:requestId", ns2)
Output
<?xml version="1.0" encoding="UTF-8"?>
<TokenRequest xmlns="http://whatever/api" xmlns:common="http://whatever/common">
<common:header>
<common:requestId>12345</common:requestId>
</common:header>
<software>
<requestId>ABCDE</requestId>
</software>
</TokenRequest>
Upvotes: 2