Find all nodes by attribute in XML using Python 2

后端 未结 2 796
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-13 20:26

I have an XML file which has a lot of different nodes with the same attribute.

I was wondering if it\'s possible to find all these nodes using Python and any additi

2条回答
  •  执念已碎
    2021-01-13 20:29

    You can use built-in xml.etree.ElementTree module.

    If you want all elements that have a particular attribute regardless of the attribute values, you can use an xpath expression:

    //tag[@attr]
    

    Or, if you care about values:

    //tag[@attr="value"]
    

    Example (using findall() method):

    import xml.etree.ElementTree as ET
    
    data = """
    
        1
        2
        3
        4
        5
    
    """
    
    parent = ET.fromstring(data)
    print [child.text for child in parent.findall('.//child[@attr]')]
    print [child.text for child in parent.findall('.//child[@attr="test"]')]
    

    Prints:

    ['1', '2', '5']
    ['1', '5']
    

提交回复
热议问题