29

If I'm parsing an XML document using lxml, is it possible to view a text representation of an element? I tried to do :

print repr(node)

but this outputs

<Element obj at b743c0>

What can I use to see the node like it exists in the XML file? Is there some to_xml method or something?

Geo
  • 93,257
  • 117
  • 344
  • 520

1 Answers1

49

From http://lxml.de/tutorial.html#serialisation

>>> root = etree.XML('<root><a><b/></a></root>')

>>> etree.tostring(root)
b'<root><a><b/></a></root>'

>>> print(etree.tostring(root, xml_declaration=True))
<?xml version='1.0' encoding='ASCII'?>
<root><a><b/></a></root>

>>> print(etree.tostring(root, encoding='iso-8859-1'))
<?xml version='1.0' encoding='iso-8859-1'?>
<root><a><b/></a></root>

>>> print(etree.tostring(root, pretty_print=True))
<root>
  <a>
    <b/>
  </a>
</root>
Percival Ulysses
  • 1,133
  • 11
  • 18
Jeff Ober
  • 4,967
  • 20
  • 15