0

I am trying to create an XML export from a python application and need to structure the file in a specific way for the external recipient of the file.

The root node needs to be namespaced, but the child nodes should not.

The root node of should look like this:

<ns0:SalesInvoice_Custom_Xml xmlns:ns0="http://EDI-export/Invoice">...</ns0:SalesInvoice_Custom_Xml>

I have tried to generate the same node using the lxml library on Python 2.7, but it does not behave as expected.

Here is the code that should generate the root node:

def create_edi(self, document):
    _logger.info("INFO: Started creating EDI invoice with invoice number %s", document.number)
    rootNs = etree.QName("ns0", "SalesInvoice_Custom_Xml")
    doc = etree.Element(rootNs, nsmap={
        'ns0': "http://EDI-export/Invoice"
    })

This gives the following output

<ns1:SalesInvoice_Custom_Xml xmlns:ns0="http://EDI-export/Invoice" xmlns:ns1="ns0">...</ns1:SalesInvoice_Custom_Xml>

What should I change in my code to get lxml to generate the correct root node

1 Answer 1

2

You need to use

rootNs = etree.QName(ns0, "SalesInvoice_Custom_Xml")

with

ns0 = "http://EDI-export/Invoice"

The whole data structure itself is agnostic of any namespace mapping you might apply later, i. e. the tags know the true namespaces (e. g. http://EDI-export/Invoice) not their mapping (e. g. ns0).

Later, when you finally serialize this into a string, a namespace mapping is needed. Then (and only then) a namespace mapping will be used.

Also, after parsing you can ask the etree object what namespace mapping had been found during parsing. But that is not part of the structure, it is just additional information about how the structure had been encoded as string. Consider that the following two XMLs are logically equal:

<x:tag xmlns:x="namespace"></x:tag>

and

<y:tag xmlns:y="namespace"></y:tag>

After parsing, their structures will be equal, their namespace mappings will not.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.