2016-08-13 68 views
0

我有以下代碼:如何獲得所有元素的路徑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 

但是,我需要得到不是列表元素的路徑,而是屬性的路徑。這裏是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 
+0

這是極不可能的,你可以讓'的getPath()'給你。該索引是生成的XPath中唯一明確的唯一內容。您可以嘗試在循環中手動修改路徑。找到節點'/ Item/Purchases/Purchase [1]'並用你想要的謂詞替換'[1]',在隨後的所有迭代中替換爲相同的值。 – Tomalak

回答

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