Get list of XML attribute values in Python

前端 未结 7 1466
有刺的猬
有刺的猬 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:57

    My preferred python xml library is lxml , which wraps libxml2.
    Xpath does seem the way to go here, so I'd write this as something like:

    from lxml import etree
    
    def getValues(xml, category):
        return [x.attrib['value'] for x in 
                xml.findall('/parent[@name="%s"]/*' % category)]
    
    xml = etree.parse(open('filename.xml'))
    
    >>> print getValues(xml, 'CategoryA')
    ['a1', 'a2', 'a3']
    >>> print getValues(xml, 'CategoryB')
    ['b1', 'b2', 'b3]
    

提交回复
热议问题