如何使用LXML递归查找XML标记?

67
<?xml version="1.0" ?>
<data>
    <test >
        <f1 />
    </test >
    <test2 >
        <test3>
         <f1 />
        </test3>
    </test2>
    <f1 />
</data>

使用lxml库,能够递归查找标签"f1"吗?我尝试过findall方法,但它只适用于直接子节点。

我认为我应该使用BeautifulSoup来实现这个功能!!!

2个回答

103

您可以使用XPath进行递归搜索:

>>> from lxml import etree
>>> q = etree.fromstring('<xml><hello>a</hello><x><hello>b</hello></x></xml>')
>>> q.findall('hello')     # Tag name, first level only.
[<Element hello at 414a7c8>]
>>> q.findall('.//hello')  # XPath, recursive.
[<Element hello at 414a7c8>, <Element hello at 414a818>]

48

iterfind() 遍历所有匹配路径表达式的元素。

findall() 返回匹配元素的列表。

find() 高效地返回第一个匹配项。

findtext() 返回第一个匹配项的文本内容(`.text`)。

示例:

>>> root = etree.XML("<root><a x='123'>aText<b/><c/><b/></a></root>")
#Find a child of an Element:
>>> print(root.find("b"))
None
>>> print(root.find("a").tag)
a
#Find an Element anywhere in the tree:
>>> print(root.find(".//b").tag)
b
>>> [ b.tag for b in root.iterfind(".//b") ]
['b', 'b']
#Find Elements with a certain attribute:
>>> print(root.findall(".//a[@x]")[0].tag)
a
>>> print(root.findall(".//a[@y]"))
[]

参考: http://lxml.de/tutorial.html#elementpath

(本答案是从上述链接内容中精选而来的相关部分)


2
请解释为什么需要使用.//b而不是b - Pynchia
用4行代码比lxml文档解释得更好。谢谢! - user3507825

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接