0

So this is the xml output I require:

<?xml version="1.0" encoding="utf-8"?>
<fooList action="add" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <foo>
        <bar>1</bar>
    </foo>
</fooList>

I am using the xmltodict python library to generate this output from a dictionary. The only problem is when I try to add the fooList tag on the top, it copies the whole string to the closing tag when it should just end in fooList. Sample of that:

 <?xml version="1.0" encoding="utf-8"?>
    <fooList action="add" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <foo>
            <bar>1</bar>
        </foo>
    </fooList action="add" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

python code:

entry = {
    '<fooList action="add" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance': {
        "foo": {
            "bar": 1,
        }
    }
}

xml = xmltodict.unparse(entry, pretty=True)
python_help
  • 121
  • 1
  • 12

1 Answers1

0

If you try the other way around you can see the mistake in your code:

import xmltodict

x_to_dic = xmltodict.parse("""<?xml version="1.0" encoding="utf-8"?>
<fooList action="add" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <foo>
        <bar>1</bar>
    </foo>
</fooList>""")
# Dictonary of xml is
print(x_to_dic)

entry = {'fooList': {'@action': 'add', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'foo': {'bar': '1'}}}

dic_to_x = xmltodict.unparse(entry, pretty=True)
# XML of dictonary is
print(dic_to_x)

Dictionary:

{'fooList': {'@action': 'add', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'foo': {'bar': '1'}}}

XML:

<?xml version="1.0" encoding="utf-8"?>
<fooList action="add" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <foo>
        <bar>1</bar>
    </foo>
</fooList>

Comparison;

Yours:
{'<fooList action="add" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance': {"foo": {"bar": 1,}}}
Generated from XML:
{'fooList': {'@action': 'add', '@xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'foo': {'bar': '1'}}}
Hermann12
  • 1,709
  • 2
  • 5
  • 14