Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I view a text representation of an lxml element?

Tags:

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?

like image 356
Geo Avatar asked Oct 14 '09 17:10

Geo


People also ask

What does lxml do in Python?

lxml is a Python library which allows for easy handling of XML and HTML files, and can also be used for web scraping. There are a lot of off-the-shelf XML parsers out there, but for better results, developers sometimes prefer to write their own XML and HTML parsers.

What is Etree in lxml?

Parsing from strings and files. lxml. etree supports parsing XML in a number of ways and from all important sources, namely strings, files, URLs (http/ftp) and file-like objects. The main parse functions are fromstring() and parse(), both called with the source as first argument.

Is lxml in Python standard library?

There is a lot of documentation on the web and also in the Python standard library documentation, as lxml implements the well-known ElementTree API and tries to follow its documentation as closely as possible. The recipes in Fredrik Lundh's element library are generally worth taking a look at.


1 Answers

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> 
like image 95
Jeff Ober Avatar answered Sep 28 '22 16:09

Jeff Ober