【问题标题】:How to find recursively for a tag of XML using LXML?如何使用 LXML 递归查找 XML 标记?
【发布时间】:2010-04-27 16:28:26
【问题描述】:
<?xml version="1.0" ?>
<data>
    <test >
        <f1 />
    </test >
    <test2 >
        <test3>
         <f1 />
        </test3>
    </test2>
    <f1 />
</data>

使用 lxml 是否可以递归地找到标签“ f1 ”?我尝试了 findall 方法,但它只适用于直系子女。

我想我应该为此选择 BeautifulSoup !!!

【问题讨论】:

    标签: python xml find lxml


    【解决方案1】:

    您可以使用 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>]
    

    【讨论】:

      【解决方案2】:

      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

      (此答案为本链接内容的相关选择性选择)

      【讨论】:

      • 请解释为什么您需要".//b" 而不仅仅是"b"
      猜你喜欢
      • 2016-07-13
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 2010-11-04
      • 2011-04-25
      相关资源
      最近更新 更多