Get list of XML attribute values in Python

前端 未结 7 1560
有刺的猬
有刺的猬 2020-12-31 07:37

I need to get a list of attribute values from child elements in Python.

It\'s easiest to explain with an example.

Given some XML like this:

&         


        
7条回答
  •  -上瘾入骨i
    2020-12-31 07:43

    In Python 3.x, fetching a list of attributes is a simple task of using the member items()

    Using the ElementTree, below snippet shows a way to get the list of attributes. NOTE that this example doesn't consider namespaces, which if present, will need to be accounted for.

        import xml.etree.ElementTree as ET
    
        flName = 'test.xml'
        tree = ET.parse(flName)
        root = tree.getroot()
        for element in root.findall(''):
            attrList = element.items()
            print(len(attrList), " : [", attrList, "]" )
    

    REFERENCE:

    Element.items()
    Returns the element attributes as a sequence of (name, value) pairs.
    The attributes are returned in an arbitrary order.

    Python manual

提交回复
热议问题