0

I use xmltodict to convert Python dictionaries to XML. I would like to include the namespaces. What I've come up with is this:

xml_dict = {
    "http://namespace.org:workflow":
        {"action-list": "..."}
}
namespaces = {"http://namespace.org": "ws"}
xml = xmltodict.unparse(xml_dict, namespaces=namespaces,
                        pretty=True, short_empty_elements=True, full_document=False)

That gives me the result:

<ws:workflow>
    <action-list>...</action-list>
</ws:workflow>

How can I include the namespaces in the result? I would like something like this:

<ws:workflow xmlns:ws="http://namespace.org">

Is there a simple solution using xmltodict?

Note: I've checked all keyword arguments in the source code of unparse and _emit functions. I guess the preprocessor argument will be the key to a better solution. But it's not documented.

1 Answers1

0

Not nice, and not a general solution to add all the namespaces, but works.

import xmltodict


xml_dict = {
    "http://namespace.org:workflow":
        {
            "@REPLACE_THIS": "http://namespace.org",
            "action-list": "..."
        }
}
namespaces = {"http://namespace.org": "ws"}
xml = xmltodict.unparse(xml_dict, namespaces=namespaces, pretty=True, short_empty_elements=True, full_document=False)
xml = xml.replace("REPLACE_THIS", "xmlns:ws", 1)
print(xml)

That gives me exactly what I want:

<ws:workflow xmlns:ws="http://namespace.org">
    <action-list>...</action-list>
</ws:workflow>

The third argument in the replace function makes it sure that not other occurrences of "REPLACE_THIS" will be replaced, just the first one.