Get list of XML attribute values in Python

前端 未结 7 1606
有刺的猬
有刺的猬 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条回答
  •  醉话见心
    2020-12-31 07:47

    ElementTree 1.3 (unfortunately not 1.2 which is the one included with Python) supports XPath like this:

    import elementtree.ElementTree as xml
    
    def getValues(tree, category):
        parent = tree.find(".//parent[@name='%s']" % category)
        return [child.get('value') for child in parent]
    

    Then you can do

    >>> tree = xml.parse('data.xml')
    >>> getValues(tree, 'CategoryA')
    ['a1', 'a2', 'a3']
    >>> getValues(tree, 'CategoryB')
    ['b1', 'b2', 'b3']
    

    lxml.etree (which also provides the ElementTree interface) will also work in the same way.

提交回复
热议问题