Find element by text with XPath in ElementTree

后端 未结 3 1843
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 21:31

Given an XML like the following:


    A
    B

How c

3条回答
  •  温柔的废话
    2020-12-03 22:03

    If you want to use the standard library ElementTree, rather than lxml, you can use iteration to find all sub elements with a particular text value. For example:

    import sys
    import xml.etree.ElementTree as etree
    
    s = """
        A
        B
    """
    
    e = etree.fromstring(s)
    
    if sys.version_info < (2, 7):
        found = [element for element in e.getiterator() if element.text == 'A']
    else:
        found = [element for element in e.iter() if element.text == 'A']
    
    print found[0].text # This prints 'A', honestly!
    

    Note: you may want to perform some stripping of the text value of your elements in the list comprehension.

    Edit This will work to any depth in your XML tree. For example,

    s = """
        A
        A
    """
    
    found = [element for element in e.getiterator() if element.text == 'A']
    
    for f in found:
        print f
    

    will print

    
    
    

提交回复
热议问题