[英]Python lxml: How to traverse back up a tree
I have the following python code 我有以下python代码
import lxml.etree
root = lxml.etree.parse("../../xml/test.xml")
path="./pages/page/paragraph[contains(text(),'ash')]"
para = root.xpath(path)
once i reach the para node, i dont want to go any further. 一旦我到达了para节点,我就不想再走了。 Now i want to travel back up to the root and look at all of the <paragraph>
nodes. 现在,我想回到根目录并查看所有<paragraph>
节点。 Is there a way to travel back up the tree. 有没有办法回去树上。
Or look at it this way. 还是这样看。 I want the subtree between root
and para
. 我想要root
和para
之间的子树。 How would i do that? 我该怎么办?
For reference, here is the xml 供参考,这是xml
<document>
<pages>
<page>
<paragraph>XBV</paragraph>
<paragraph>GFH</paragraph>
</page>
<page>
<paragraph>ash</paragraph>
<paragraph>lplp</paragraph>
</page>
</pages>
</document>
now in this case, i want the nodes XBV and GFH. 现在在这种情况下,我想要节点XBV和GFH。 How is that possible? 那怎么可能?
..
would bring you one level up the tree. ..
会带您上树。
But, I think preceding
is something you are looking for: 但是,我认为preceding
是你正在寻找的东西:
The preceding axis indicates all the nodes that precede the context node in the document except any ancestor, attribute and namespace nodes. 前一个轴表示文档中上下文节点之前的所有节点,但所有祖先,属性和名称空间节点除外。
./pages/page/paragraph[contains(text(),'ash')]//preceding::paragraph
Sample code: 样例代码:
import lxml.etree
data = """
<document>
<pages>
<page>
<paragraph>XBV</paragraph>
<paragraph>GFH</paragraph>
</page>
<page>
<paragraph>ash</paragraph>
<paragraph>lplp</paragraph>
</page>
</pages>
</document>
"""
tree = lxml.etree.fromstring(data)
print [item.text for item in tree.xpath("./pages/page/paragraph[contains(text(),'ash')]//preceding::paragraph")]
Prints: 打印:
['XBV', 'GFH']
Go up and get all previous page
(only page) node and paragraph
node inside them and extract text from them- 上去,让所有先前page
(仅页)节点, paragraph
节点内他们从文本中提取他们-
>>>expresson = "./pages/page/paragraph[contains(text(),'ash')]//preceding::page//paragraph"
>>>x= [i.text for i in expresson]
>>>['XBV', 'GFH']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.