2012-07-03 43 views
0

我在Python中使用minidom,我想搜索節點(書籍)列表,並搜索屬性「name」等於「statistics」的每個book節點,I想要打印節點引用。下面是我想處理XML文件的例子:在Python中使用minidom提取節點引用ID

<book id='123'> 
    <name>statistics</name> 
</book> 

<book id='234'> 
    <name>mathematics</name> 
</book> 

<book id='345'> 
    <name>statistics</name> 
</book> 

所需的輸出是:

123 
345 

我如何能做到這一點任何想法?

+1

迭代通過每個節點,測試,看看是否能節點包含名爲「統計數據」,保存ID。 –

+0

你已經選擇了一個XML庫來使用,但是你沒有在你的問題中展示它的任何用處。如果您發佈有效的XML片段,這會更有幫助。 – MattH

+0

這幾乎是我試圖做的,但我沒有設法保存身份證。你會碰巧知道如何做到這一點? – user1499144

回答

1

遍歷book元素並查看名稱節點以查看其統計信息。如果它打印出書籍節點的屬性,則爲id。

import xml.dom.minidom 
Document = "<books>\ 
      <book id='123'>\ 
       <name>statistics</name>\ 
      </book>\ 
      <book id='234'>\ 
       <name>mathematics</name>\ 
      </book>\ 
      <book id='345'>\ 
       <name>statistics</name>\ 
      </book></books>" 

dom = xml.dom.minidom.parseString(Document) 
for book in dom.getElementsByTagName("book"): 
    node = book.getElementsByTagName("name")[0] 
    if node.firstChild.data.strip().lower() == "statistics": 
     print int(book.getAttribute("id").strip()) 

輸出

123 
345 
+0

我的帖子很遺憾缺乏語法着色。我做錯了什麼? –

+0

完美的,它成功了!非常感謝! – user1499144