2013-05-03 60 views
1

這裏是XML樹,我穿越的樣本:的Python/LXML - 獲得「孫子」,從etree

<entry dataset="Swiss-Prot" created="1993-07-01+01:00" modified="2013-04-03+01:00" version="144"> 
    <accession>P31750</accession> 
    <accession>Q62274</accession> 
    <accession>Q6GSA6</accession> 
    <name>AKT1_MOUSE</name> 
    <protein> 
    <recommendedName> 
     <fullName>RAC-alpha serine/threonine-protein kinase</fullName> 
     <ecNumber>2.7.11.1</ecNumber> 
    </recommendedName> 
    <alternativeName> 
     <fullName>AKT1 kinase</fullName> 
    </alternativeName><alternativeName> 
     <fullName>Protein kinase B</fullName> 
    .......... 

我試圖去recommendedName,這裏是當前Python代碼我使用到達它:

protein = e.find("{http://uniprot.org/uniprot}protein") 
r_names = [] 
for child in protein.find("recommendedName"): 
    for subchild in child.find("fullName"): 
      r_names.append(subchild.text) 

e在這種情況下代表從<entry></entry>。當我嘗試運行此代碼,我從Python解釋器收到以下錯誤:

for child in protein.find("recommendedName"): 
    TypeError: 'NoneType' object is not iterable 

所以這是告訴我,這裏child不是一個迭代的對象。我真的不明白,因爲protein肯定是可迭代的,所以如果它finds它應該是可迭代的。無論如何,我如何使用lxml API訪問孫子節點recommendedNamealternativeName

回答

3
for child in protein.find("recommendedName"): 
    TypeError: 'NoneType' object is not iterable 

錯誤消息是說protein.find正在返回None。因此找不到recommendedName元素。

由於您使用的一個命名空間來找到protein,你可能需要使用

for child in protein.find("{http://uniprot.org/uniprot}recommendedName") 

或更好,但

for child in protein.xpath("uniprot:recommendedName", 
          namespaces = dict(uniprot='http://uniprot.org/uniprot')) 
+0

十分感謝了很多,由於某種原因,我想我只需要命名空間的根,它的孩子,和他們的兄弟姐妹。我沒有意識到我也可以將它用於嵌套元素。 – Houdini 2013-05-03 19:47:49