1

Trying to do this using xmltodict.unparse:

I have this structure in json:

"organisations": [
    {"organisation": "org1"}, 
    {"organisation": "org2"}, 
    {"organisation": "org3"}
]

But comes out like this in xml:

<organisations><organisation>org1</organisation></organisations>
<organisations><organisation>org2</organisation></organisations>
<organisations><organisation>org2</organisation></organisations>

I wanted like this:

<organisations>
    <organisation>org1</organisation>
    <organisation>org2</organisation>
    <organisation>org2</organisation>
</organisations>

Im using xmltodict.unparse

def dict_to_xml(d, pretty_print=False, indent=DEFAULT_INDENT, document_root="root"):
    if len(d.keys()) != 1:
        d = {
            document_root: d
        }

    res = xmltodict.unparse(d, indent=indent, short_empty_elements=True)

    if pretty_print:
        res = pretty_print_xml(res).strip()

    return res

Anyone know what to do without hacking xmltodict??

thanks

ptim
  • 14,902
  • 10
  • 83
  • 103
Elias
  • 81
  • 1
  • 13

1 Answers1

2

I don't much about XML, but I got curious about this question and noticed:

Lists that are specified under a key in a dictionary use the key as a tag for each item.

My approach was to reverse engineer the result you're after:

expected = '''
    <organisations>
        <organisation>org1</organisation>
        <organisation>org2</organisation>
        <organisation>org2</organisation>
    </organisations>
'''

print(json.dumps(xmltodict.parse(expected), indent=4))

output:

{
    "organisations": {
        "organisation": [
            "org1",
            "org2",
            "org2"
        ]
    }
}

And "round tripping" that, gives the result you're after:

reverse = {
    "organisations": {
        "organisation": [
            "org1",
            "org2",
            "org2"
        ]
    }
}

print(xmltodict.unparse(reverse, pretty=True))

output:

<?xml version="1.0" encoding="utf-8"?>
<organisations>
    <organisation>org1</organisation>
    <organisation>org2</organisation>
    <organisation>org2</organisation>
</organisations>

HTH!

ptim
  • 14,902
  • 10
  • 83
  • 103