获取Python中的XML属性值列表

时间:2008-09-17 20:32:04

标签: python xml xpath parent-child xml-attribute

我需要从Python中的子元素中获取属性值列表。

最简单的解释一个例子。

给出一些这样的XML:

<elements>
    <parent name="CategoryA">
        <child value="a1"/>
        <child value="a2"/>
        <child value="a3"/>
    </parent>
    <parent name="CategoryB">
        <child value="b1"/>
        <child value="b2"/>
        <child value="b3"/>
    </parent>
</elements>

我希望能够做到这样的事情:

>>> getValues("CategoryA")
['a1', 'a2', 'a3']
>>> getValues("CategoryB")
['b1', 'b2', 'b3']

它看起来像XPath的工作,但我对所有建议持开放态度。我也想听听你最喜欢的Python XML库。

7 个答案:

答案 0 :(得分:7)

我不是Python的老手,但这是使用libxml2的XPath解决方案。

import libxml2

DOC = """<elements>
    <parent name="CategoryA">
        <child value="a1"/>
        <child value="a2"/>
        <child value="a3"/>
    </parent>
    <parent name="CategoryB">
        <child value="b1"/>
        <child value="b2"/>
        <child value="b3"/>
    </parent>
</elements>"""

doc = libxml2.parseDoc(DOC)

def getValues(cat):
    return [attr.content for attr in doc.xpathEval("/elements/parent[@name='%s']/child/@value" % (cat))]

print getValues("CategoryA")

结果......

['a1', 'a2', 'a3']

答案 1 :(得分:6)

ElementTree 1.3(遗憾的是不是1.2包含在Python中的那个)supports XPath是这样的:

import elementtree.ElementTree as xml

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

然后你可以做

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

lxml.etree(也提供ElementTree接口)也将以相同的方式工作。

答案 2 :(得分:3)

使用标准的W3 DOM,例如stdlib的minidom或pxdom:

def getValues(category):
    for parent in document.getElementsByTagName('parent'):
        if parent.getAttribute('name')==category:
            return [
                el.getAttribute('value')
                for el in parent.getElementsByTagName('child')
            ]
    raise ValueError('parent not found')

答案 3 :(得分:2)

由于其易于使用,我必须承认我是xmltramp的粉丝。

访问上述内容变为:

  import xmltramp

  values = xmltramp.parse('''...''')

  def getValues( values, category ):
    cat = [ parent for parent in values['parent':] if parent(name) == category ]
    cat_values = [ child(value) for child in parent['child':] for parent in cat ]
    return cat_values

  getValues( values, "CategoryA" )
  getValues( values, "CategoryB" )

答案 4 :(得分:2)

您可以使用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')]

如果你正在使用HTML / XML,我建议你看一下BeautifulSoup。它类似于DOM树,但包含更多功能。

答案 5 :(得分:2)

我首选的python xml库是lxml,它包装了libxml2 Xpath看起来似乎是这里的方式,所以我写这样的东西:

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]

答案 6 :(得分:0)

在Python 3.x中,获取属性列表是使用成员items()

的简单任务

使用ElementTree,下面的代码段显示了获取属性列表的方法。 请注意,此示例不考虑名称空间,如果存在,则需要将其考虑在内。

    import xml.etree.ElementTree as ET

    flName = 'test.xml'
    tree = ET.parse(flName)
    root = tree.getroot()
    for element in root.findall('<child-node-of-root>'):
        attrList = element.items()
        print(len(attrList), " : [", attrList, "]" )

<强>参考:

  

Element.items()
      将元素属性作为(名称,值)对的序列返回       属性以任意顺序返回。

Python manual