如何使用XPath lxml Python选择直接子级?
我正在编写一些lxml代码,但不了解它们之间的区别-我想直接选择父项下面的子项:如何使用XPath lxml Python选择直接子级?,python,xpath,lxml,python-3.5,Python,Xpath,Lxml,Python 3.5,我正在编写一些lxml代码,但不了解它们之间的区别-我想直接选择父项下面的子项: xml = '<parent><child></child><parent>' root = lxml.etree.fromstring(xml) root.xpath('child') 选择不带轴的元素时,其语法缩写为: child::the_element 等于 the_element 当前上下文 以句点和正斜杠(./)为前缀的表达式显式使用当前上下
xml = '<parent><child></child><parent>'
root = lxml.etree.fromstring(xml)
root.xpath('child')
选择不带轴的元素时,其语法缩写为:
child::the_element
等于
the_element
当前上下文
以句点和正斜杠(./)为前缀的表达式显式使用当前上下文作为上下文。例如,以下表达式引用当前上下文中的所有元素:
./author
请注意,这相当于以下内容:
author
在这种情况下,表达式
child
和/child
给出相同的结果。这是因为child
隐式假定了一个上下文节点,在XPath中称为
。要查看Python/lxml/文档中的上下文节点是什么,只需计算
。更正XML文档中可能导致格式良好错误的键入错误后:
>>> xml = '<parent><child></child></parent>'
>>> root = lxml.etree.fromstring(xml)
>>> root.xpath('.')
[<Element parent at 0x1038446c8>]
首先查找子元素
元素:
>>> child = root.xpath('child')[0]
然后使用此元素作为上下文计算XPath表达式:
>>> child.xpath('//other')
[<Element other at 0x1038446c8>, <Element other at 0x105380348>]
>>> child.xpath('.//other')
[<Element other at 0x105380348>]
>child.xpath(“//其他”)
[, ]
>>>xpath('.//其他')
[]
在这种情况下,XPath表达式开头的
实际上会影响结果列表,只有//other
返回正确的结果
>>> child = root.xpath('child')[0]
>>> child.xpath('//other')
[<Element other at 0x1038446c8>, <Element other at 0x105380348>]
>>> child.xpath('.//other')
[<Element other at 0x105380348>]