XPath:如何找到所有文本节点的父元素及其类
对于所有文本节点,我该如何找到它们的父元素的类和标签类型呢?
1 个回答
1
根据XPath的文档,其实并不难。这里有一个我特意准备的XML文件:
<root>
<child1>
<text>Text1</text>
</child1>
<child2>
<text>Text2</text>
</child2>
<child3>
<text>Text3</text>
</child3>
<child4>
<text>Text4</text>
</child4>
</root>
现在我们使用lxml库,这个库支持XPath(而内置的Python XML库是没有这个功能的),我们来看看:
>>> from lxml import etree
>>> root = etree.parse(path).getroot()
>>> for p in root.xpath('//text/..'):
print p.tag
child1
child2
child3
child4