2016-10-28 43 views
1
<storage> 
    <record> 
     <values> 
     <points>99999999</points> 
     <points>Mr</points> 
     <points>Marvin</points> 
     <points>Homes</points> 
     <points>hardware</points> 
     <points>true</points> 
     <points>de</points> 
     <points>6</points> 
     <points>false</points> 
     </values> 
    </record> 
    </storage> 

你好,如何用python(xml.etree.ElementTree)解決下一個問題?

我試圖改變一些XML值與Python(xml.etree.ElementTree)。 這是xml數據的一小部分。

appelation=re.compile("Mr") 
for fname in root.iter('points'): 

    if appelation.match(str(pTest)): 
     fname.text="New Mr/Mrs" 
     ## here i am trying to edit the next iter (<points>Marvin</points>) 
     ##fname.next().text="New name" -> doesnt work 

任何建議如何解決下一個iter? xml文件有很多名爲<「points」>的標籤,並且值始終不一樣。

+0

你可以設置一個變量(match_found = TRUE),然後繼續下一個迭代 – Moberg

+0

我不明白的問題。什麼是「pTest」的價值? – lucasnadalutti

+0

您使用哪個ElementTree? xml.etree.ElementTree或lxml.etree? –

回答

0

我假設您使用的是xml.etree.ElementTree,因爲它是標準庫的一部分。請看下面的代碼片段:

appelation = re.compile('Mr') 
points = root.iter('points') 
for node in points: 
    if appelation.match(node.text): 
     node.text = 'Monsieur' 
     node = next(points) 
     node.text = 'Francois' 
     break 

ElementTree.dump(根)

在這個片段中,points是一個迭代我們用它來獲得下一個點和搜索。一旦我們找到了我們正在尋找的節點(Mr),我們就可以對該節點和下一個節點執行一些操作(通過在所述迭代器上調用next)。

輸出:

<storage> 
    <record> 
     <values> 
     <points>99999999</points> 
     <points>Monsieur</points> 
     <points>Francois</points> 
     <points>Homes</points> 
     <points>hardware</points> 
     <points>true</points> 
     <points>de</points> 
     <points>6</points> 
     <points>false</points> 
     </values> 
    </record> 
    </storage> 

更新

如果要修改這個節點,下一節點,和前一個節點;那麼你需要跟蹤前一個節點,因爲迭代器無法返回。最簡單的方法是使用一個堆棧(一listcollections.deque會做):

appelation = re.compile('Mr') 
points = root.iter('points') 
nodes_stack = [] 
for node in points: 
    if appelation.match(node.text): 
     # Modify this node 
     node.text = 'Monsieur' 

     # Modify next node 
     next_node = next(points) 
     next_node.text = 'Francois' 

     # Modify previous node 
     previous_node = nodes_stack.pop() 
     previous_node.text = 'modified' 

     # Keep popping the stack the get to previous nodes 
     # in reversed order 

     ElementTree.dump(root) 
     break 
    else: 
     nodes_stack.append(node) 
+0

謝謝:)多數民衆贊成正是我正在尋找:) –

+0

請注意,這將提高未被捕獲的'StopIteration',以防'Monsieur'是輸入中的最後一項。您可能想要捕捉它(使用普通的'try' /'except'子句),並引發更多說話異常(例如'ValueError(「Monsieur」之後的缺失值)')以便於調試。 – Alfe

+0

好點。還有一種情況是,Mr *沒有發現我們也應該處理。 –