lxml and xpath(?)

Pete Forman petef4+usenet at gmail.com
Thu Oct 27 02:56:44 EDT 2016


Peter Otten <__peter__ at web.de> writes:

> root = etree.fromstring(s)
> for server in root.xpath("./server"):
>     servername = server.xpath("./name/text()")[0]

When working with lxml I prefer to use this Python idiom.

    servername, = server.xpath("./name/text()")

That enforces a single result. The original code will detect a lack of
results but if the query returns multiple results when only one is
expected then it silently returns the first.

-- 
Pete Forman



More information about the Python-list mailing list