Why does this XML attribute fire a validation error and why is it even there?

Viewed 62

I create an xml-fil and run into a problem. I have simplified my code as much as I can to show the error. I have a reference to Microsoft XML 6.0 in my project. When I run this code

Sub simpleTest()
    Dim xDoc As New DOMDocument60
    Dim n0 As IXMLDOMNode
    Dim n1 As IXMLDOMElement
    Dim n2 As IXMLDOMElement
    Dim blValiderad As Boolean
    Const file = "c:\temp\abc.xml"
    
    xDoc.async = False
    xDoc.validateOnParse = False
    xDoc.resolveExternals = False
    xDoc.preserveWhiteSpace = True
    Set n0 = xDoc.createProcessingInstruction("xml", "version='1.0' encoding='UTF-8'")
    xDoc.appendChild n0
    Set n1 = xDoc.createElement("Document")
    n1.setAttribute "xmlns", "urn:iso:std:iso:20022:tech:xsd:pain.001.001.03"
    n1.setAttribute "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"
    Set n2 = xDoc.createElement("CstmrCdtTrfInitn")
    n2.Text = "hello"
    n1.appendChild n2  'CstmrCdtTrfInitn
    xDoc.appendChild n1 'Document
    xDoc.Save file
End Sub

it produces this xml-expression

<?xml version="1.0"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CstmrCdtTrfInitn xmlns="">
hello
</CstmrCdtTrfInitn>
</Document>

On validation it produces this error:

1072897501; Validate failed because the document does not contain exactly one root node.

The problem seems to be the empty attribute xmlns="" of CstmrCdtTrfInitn. When I remove it from the file there is no validation errors. Why is that and why is it even produced by my code?

1 Answers

As far as I understand, CreateElement("some_text") is a shorthand for createNode(Type:=NODE_ELEMENT, Name:="some_text", NamespaceURI:="").

Since that NamespaceURI doesn't match the parent element, the attribute gets created.

Instead, use createNode and specify the namespace:

Dim xDoc As New DOMDocument60
Dim n0 As IXMLDOMNode
Dim n1 As IXMLDOMElement
Dim n2 As IXMLDOMElement
Dim blValiderad As Boolean
Const file = "c:\temp\abc.xml"

xDoc.async = False
xDoc.validateOnParse = False
xDoc.resolveExternals = False
xDoc.preserveWhiteSpace = True
Set n0 = xDoc.createProcessingInstruction("xml", "version='1.0' encoding='UTF-8'")
xDoc.appendChild n0
Set n1 = xDoc.createElement("Document")
n1.setAttribute "xmlns", "urn:iso:std:iso:20022:tech:xsd:pain.001.001.03"
n1.setAttribute "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"
Set n2 = xDoc.createNode(NODE_ELEMENT, "CstmrCdtTrfInitn", "urn:iso:std:iso:20022:tech:xsd:pain.001.001.03")
n2.Text = "hello"
n1.appendChild n2  'CstmrCdtTrfInitn
xDoc.appendChild n1 'Document
Debug.Print xDoc.XML
Related