I want to create an XML using MSXML in VBA. The target output is pretty basic:
<Main xmlns="http://www.myurl.com/xml">
<Info>
<BaseData>
<CreationDate>2021-11-10</CreationDate>
<Hardware>
<Frquency>100</Frquency>
</Hardware>
<SomeCode>000000_0000000</SomeCode>
<SomeName>HW GPU SoC 1</SomeName>
</BaseData>
</Info>
</Main>
However my code is generating an xmlns attribute in the "Info" element and I don't know why:
<Main xmlns="http://www.myurl.com/xml">
<Info xmlns="">
<BaseData>
<CreationDate>2021-11-10</CreationDate>
<Hardware>
<Frquency>100</Frquency>
</Hardware>
<SomeCode>000000_0000000</SomeCode>
<SomeName>HW GPU SoC 1</SomeName>
</BaseData>
</Info>
</Main>
Here is the code:
Dim doc As New MSXML2.DOMDocument60
Dim root As IXMLDOMNode
Dim info As IXMLDOMElement, baseData As IXMLDOMElement
Dim someCode As IXMLDOMElement, someName As IXMLDOMElement, hardware As IXMLDOMElement, freq As IXMLDOMElement, creationDate As IXMLDOMElement
Dim namesp As String
namesp = "http://www.myurl.com/xml"
Set root = doc.createNode(NODE_ELEMENT, "Main", namesp)
doc.appendChild root
Set info = doc.createElement("Info")
Set baseData = doc.createElement("BaseData")
Set someCode = doc.createElement("SomeCode")
Set someName = doc.createElement("SomeName")
Set hardware = doc.createElement("Hardware")
Set freq = doc.createElement("Frquency")
Set creationDate = doc.createElement("CreationDate")
freq.Text = "100"
hardware.appendChild freq
creationDate.Text = "2021-11-10"
someCode.Text = "000000_0000000"
someName.Text = "HW GPU SoC 1"
baseData.appendChild creationDate
baseData.appendChild hardware
baseData.appendChild someCode
baseData.appendChild someName
info.appendChild baseData
root.appendChild info
doc.Save (filePath)
When I change the line to "Set info = doc.createNode(NODE_ELEMENT, "Info", namesp)" the xmlns attribute moves to BaseData. Why is that?
CodePudding user response:
In your target output all the elements belong to the http://www.myurl.com/xml namespace. They inherit the namespace from your root element.
You only create your root element with this namespace. All other elements have an empty namespace. That is why the namespace gets reset to an empty namespace in your first child.
To get your target xml output, create ALL elements using your namespace. e.g. use
Set info = doc.createNode(NODE_ELEMENT, "Info", namesp)