Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do not collapse empty nodes in XML output

I'm using python's xml.etree.ElementTree to represent an XML document. I want to output it to text but I want to keep empty elements (elements with no children) expanded, instead of collapsed. E.g., I want this:

<element></element>

Instead of this:

<element />

I'm currently using ElementTree.tostring, but I'm willing to use any other built-in python modules or functions to serialize the document, as long as I can pretty easily use an ElementTree object with it.

FYI, the reason I want to keep the elements expanded is because I want to more easily diff the output with output from a third party program which doesn't collapse empty elements.

like image 858
brianmearns Avatar asked Dec 19 '25 04:12

brianmearns


1 Answers

You can pass method="html" to the tostring() call.

Demo:

>>> import xml.etree.ElementTree as etree
>>> data = """
... <root>
...     <person/>
...     <person></person>
... </root>
... """
>>> tree = etree.fromstring(data)
>>> print etree.tostring(tree, method="html")
<root>
    <person></person>
    <person></person>
</root>
like image 159
alecxe Avatar answered Dec 20 '25 16:12

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!