lxml list in python

To create a list using lxml in Python, we can parse an XML document using the lxml library and then extract the desired data into a list. Here's an example using the xpath method:

main.py
from lxml import etree

# Example XML
xml_string = "<fruits><fruit>apple</fruit><fruit>banana</fruit><fruit>cherry</fruit></fruits>"

# Parse XML
xml = etree.fromstring(xml_string)

# Extract data into list using xpath
fruits = xml.xpath('//fruit/text()')

# Print list
print(fruits)
284 chars
14 lines

Output:

main.py
['apple', 'banana', 'cherry']
30 chars
2 lines

In the above example, we first import the etree module from the lxml library. We then define an example XML string and use the fromstring method to parse it into an XML object.

Next, we use the xpath method to extract the text content of all fruit elements in the XML. The '//fruit/text()' argument passed to the xpath method selects all fruit elements, and the /text() portion selects their text content.

Finally, we print the resulting list object.

related categories

gistlibby LogSnag