简体   繁体   中英

Include namespace in xmltodict.unparse output

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM