xmlvbams-accessmsxml6

MSXML adds default empty xmlns to all elements


I need to create an XML out of an specific xsd schema, and im useing VBA for access with the MSXML2 library. so far i can create everything but the thing is MSXML2 create default xmlns on the fields after the root even tho i specified it.

What i want to achieve:

<auditfile xmlns="urn:StandardAuditFile-Taxation-CashRegister:DK">
  <header>
  </header>
  <company>
  </company>
</auditfile>

what im getting:

<auditfile xmlns="urn:StandardAuditFile-Taxation-CashRegister:DK">
  <header xmlns="">
  </header>
  <company xmlns="">
  </company>
</auditfile>

I have an validator i can check against everything is ok, but it as soon that the xmlns="" is present i says no.

My code for generateing the start of the xml is like this.

Dim Document As Object
Set Document = CreateObject("MSXML2.DOMDocument.6.0")

Dim AuditRoot As Object
Set AuditRoot = Document.createElement("auditfile")
AuditRoot.setAttribute "xmlns", "urn:StandardAuditFile-Taxation-CashRegister:DK"
Document.appendChild AuditRoot

Set headerRoot = Document.createElement("header")
AuditRoot.appendChild headerRoot

Set companyRoot = Document.createElement("company")
AuditRoot.appendChild companyRoot

'Save the XML file
Document.Save "c:\Diamond\XML\SAT-T.xml"
'Set export to be c:\Diamond\XML\fil
MsgBox "File created at dafault location: C:\Diamond\XML\SAT-T.xml"

But as said above its different. so anyhelp to general if i can disable it or?


Solution

  • It is better to use .createNode() method instead of .createElement().

    It has 3 parameters, and one of them allows to specify a namespace.

    For the reference: createNode Method

    I used vbscript syntax, but you can easily adjust it back to VBA.

    vbscript

    Dim Document
    Set Document = CreateObject("MSXML2.DOMDocument.6.0")
    
    Dim AuditRoot, NS
    NS = "urn:StandardAuditFile-Taxation-CashRegister:DK"
    
    Set AuditRoot = Document.createNode(1, "auditfile", NS)
    Document.appendChild AuditRoot
    
    Set headerRoot = Document.createNode(1, "header", NS)
    AuditRoot.appendChild headerRoot
    
    Set companyRoot = Document.createNode(1, "company", NS)
    AuditRoot.appendChild companyRoot
    
    'Save the XML file
    Document.Save "c:\Diamond\XML\SAT-T.xml"
    'Set export to be c:\Diamond\XML\fil
    MsgBox "File created at dafault location: C:\Diamond\XML\SAT-T.xml"
    

    Output

    <auditfile xmlns="urn:StandardAuditFile-Taxation-CashRegister:DK">
        <header/>
        <company/>
    </auditfile>