Skip to content

Element Tree Serializer

The tree serializer will render an object into an element tree, that you can use to run XPATH evaluations or XSLT transformations.

The TreeSerializer depends on lxml. There is no native python ElementTree implementation because of limitations with namespaces.


>>> from lxml import etree
>>> from tests.fixtures.books.fixtures import books
>>> from xsdata.formats.dataclass.serializers import TreeSerializer
>>> serializer = TreeSerializer()
>>> serializer.config.indent = "  "
>>> result = serializer.render(books, ns_map={'bk': "urn:books"})
>>> actual = etree.tostring(result)
>>> print(actual.decode())
<bk:books xmlns:bk="urn:books">
  <book id="bk001" lang="en">
    <author>Hightower, Kim</author>
    <title>The First Book</title>
    <review>An amazing story of nothing.</review>
  <book id="bk002" lang="en">
    <author>Nagata, Suanne</author>
    <title>Becoming Somebody</title>
    <review>A masterpiece of the fine art of gossiping.</review>