如何使用属性获取lxml中所有元素的路径

时间:2016-08-13 20:05:16

标签: python xml lxml

我有以下代码:

tree = etree.ElementTree(new_xml)
for e in new_xml.iter():
    print tree.getpath(e), e.text

这将给我类似以下内容:

/Item/Purchases 

/Item/Purchases/Purchase[1] 
/Item/Purchases/Purchase[1]/URL http://tvgo.xfinity.com/watch/x/6091165185315991112/movies
/Item/Purchases/Purchase[1]/Rating R

/Item/Purchases/Purchase[2] 
/Item/Purchases/Purchase[2]/URL http://tvgo.xfinity.com/watch/x/6091165185315991112/movies
/Item/Purchases/Purchase[2]/Rating R

但是,我需要获取list元素而不是属性的路径。这是xml的样子:

<Item>
  <Purchases>
     <Purchase Country="US">
      <URL>http://tvgo.xfinity.com/watch/x/6091165US</URL>
      <Rating>R</Rating>
    </Purchase>
     <Purchase Country="CA">
      <URL>http://tvgo.xfinity.com/watch/x/6091165CA</URL>
      <Rating>R</Rating>
    </Purchase>
</Item>

我将如何获得以下路径?

/Item/Purchases 

/Item/Purchases/Purchase[@Country="US"]
/Item/Purchases/Purchase[@Country="US"]/URL http://tvgo.xfinity.com/watch/x/6091165185315991112/movies
/Item/Purchases/Purchase[@Country="US"]/Rating R

/Item/Purchases/Purchase[@Country="CA"]
/Item/Purchases/Purchase[@Country="CA"]/URL http://tvgo.xfinity.com/watch/x/6091165185315991112/movies
/Item/Purchases/Purchase[@Country="CA"]/Rating R

1 个答案:

答案 0 :(得分:1)

不漂亮,但是它可以胜任。

replacements = {}

for e in tree.iter():
    path = tree.getpath(e)

    if re.search('/Purchase\[\d+\]$', path):
        new_predicate = '[@Country="' + e.attrib['Country'] + '"]'
        new_path = re.sub('\[\d+\]$', new_predicate, path)
        replacements[path] = new_path

    for key, replacement in replacements.iteritems():
        path = path.replace(key, replacement)

    print path, e.text.strip()

为我打印:

/Item 
/Item/Purchases 
/Item/Purchases/Purchase[@Country="US"] 
/Item/Purchases/Purchase[@Country="US"]/URL http://tvgo.xfinity.com/watch/x/6091165US
/Item/Purchases/Purchase[@Country="US"]/Rating R
/Item/Purchases/Purchase[@Country="CA"] 
/Item/Purchases/Purchase[@Country="CA"]/URL http://tvgo.xfinity.com/watch/x/6091165CA
/Item/Purchases/Purchase[@Country="CA"]/Rating R
相关问题