Get list of XML attribute values in Python

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

    You can do this with BeautifulSoup

    >>> from BeautifulSoup import BeautifulStoneSoup
    >>> soup = BeautifulStoneSoup(xml)
    >>> def getValues(name):
    . . .      return [child['value'] for child in soup.find('parent', attrs={'name': name}).findAll('child')]
    

    If you're doing work with HTML/XML I would recommend you take a look at BeautifulSoup. It's similar to the DOM tree but contains more functionality.

提交回复
热议问题