xmltodict icon indicating copy to clipboard operation
xmltodict copied to clipboard

dict to xml - how to discard the parent tag repeating for conversion from list

Open sergei-sss opened this issue 2 years ago • 2 comments

Hi everyone.

From this dictionary:

feed = {
    'feed': {
        'reviewer_images': [
            {
                'reviewer_image': {
                    'url': "http://google.com"
                }
            },
            {
                'reviewer_image': {
                    'url': "http://google.com"
                }
            }
        ]
    }
}

I have got:

<?xml version="1.0" encoding="utf-8"?>
<feed>
        <reviewer_images>
                <reviewer_image>
                        <url>http://google.com</url>
                </reviewer_image>
        </reviewer_images>
        <reviewer_images>
                <reviewer_image>
                        <url>http://github.com</url>
                </reviewer_image>
        </reviewer_images>
</feed>

Is it possible to get several reviewer_image inside identical reviewer_images tag?:

<?xml version="1.0" encoding="utf-8"?>
<feed>
        <reviewer_images>
                <reviewer_image>
                      <url>http://google.com</url>
                </reviewer_image>
                <reviewer_image>
                      <url>http://github.com</url>
                </reviewer_image>
        </reviewer_images>
</feed>

sergei-sss avatar Oct 30 '22 16:10 sergei-sss

Having the same issue, any help will be appreciated.

thaikoh avatar Dec 08 '22 13:12 thaikoh

A bit late to the party:

feed = {
    'feed': {
        'reviewer_images': {
            'reviewer_image': [
                {
                    'url': "http://google.com"
                },
                {
                    'url': "http://google.com"
                }
            ]
        }
    }
}
print(xmltodict.unparse(feed, pretty=True))

Result:

<?xml version="1.0" encoding="utf-8"?>
<feed>
	<reviewer_images>
		<reviewer_image>
			<url>http://google.com</url>
		</reviewer_image>
		<reviewer_image>
			<url>http://google.com</url>
		</reviewer_image>
	</reviewer_images>
</feed>

To generate multiple <foo> you have to use { "foo": […] } and not [ {"foo": …}, {"foo": …} ].

bfontaine avatar Jul 07 '23 16:07 bfontaine