3

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.

2 Answers 2

6

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately, html output method does not properly preserve the case of tags. For instance, if you have a mixed case tag like "peasantFarmer", the opening tag is correct, but the closing tag is "peasantfarmer" (notice lower-case 'f'). Not sure if this is a bug or if its deliberate because HTML is supposed to be case insensitive (though I would have thought tag pairs still need to match).
This removes the XML declaration, even if you use xml_declaration=True.
5

Just use: ElementTree.tostring(element, short_empty_elements=False)

1 Comment

That also works when saving the whole document to a file tree.write(file_name, encoding="UTF-8", short_empty_elements=False)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.