lxml and xpath(?)
Peter Otten
__peter__ at web.de
Thu Oct 27 03:18:04 EDT 2016
Pete Forman wrote:
> 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.
Good suggestion, and for those who find the trailing comma easy to overlook:
[servername] = server.xpath("./name/text()")
More information about the Python-list
mailing list