我想从VBA生成以下XML。
<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>
我下面代码的问题是,它也在common:header节点中生成xmlns:common属性。
因此,取而代之的是:
<common:header>
我得到这个:
<common:header xmlns:common="http://whatever/api">
这是我正在使用的一段代码:
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
使用上述代码生成的完整XML如下:
<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>
如何在节点级别上消除该属性?
简单地说,有前缀的节点指向其对应的命名空间("http://whatever/common"
(,没有前缀的节点则指向默认命名空间("http://whatever/api"
(。回想一下,声明的名称空间前缀覆盖默认名称空间。
Set xeHeader = xRequest.createNode(NODE_ELEMENT, "common:header", ns2)
Set xeTmp = xRequest.createNode(NODE_ELEMENT, "common:requestId", ns2)
输出
<?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>