martinblech / xmltodict

Python module that makes working with XML feel like you are working with JSON
MIT License
5.46k stars 465 forks source link

Assigning a root elements other than root #329

Open mqnifestkelvin opened 1 year ago

mqnifestkelvin commented 1 year ago

When using the xmltodict.unparse() is a possibility of stating what the root element will be other than root when generating xml files. Thank you a response would be duly appreciated. Also anytime I convert to form xmltodict, the values are changed from their actual values to string values, which is not what I intend, I need all the values to be exact in their conversion, is there away this is also done that I am not getting. Thank you.

mqnifestkelvin commented 1 year ago

Also is there a way we can add custom indent spacing to the resulting xml file?

bfontaine commented 1 year ago

Please share a sample of your data so we can reproduce your issue.

Also is there a way we can add custom indent spacing to the resulting xml file?

Yes, you can use pretty=True + indent="<custom indent>" to specify which string to use for indentation:

doc = { "doc": { "a": 1, "b": 2 } }

print(xmltodict.unparse(doc, pretty=True, indent=" ")) # one char
print(xmltodict.unparse(doc, pretty=True, indent="\t\t")) # two tabs

Results:

<?xml version="1.0" encoding="utf-8"?>
<doc>
 <a>1</a>
 <b>2</b>
</doc>
<?xml version="1.0" encoding="utf-8"?>
<doc>
        <a>1</a>
        <b>2</b>
</doc>