2016-10-28 3 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)で次のiterを処理するにはどうすればいいですか?

私は、Python(xml.etree.ElementTree)と、いくつかのXML値を変更しようとしています。 これは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 =真)変数を設定して、次の反復 – Moberg

+0

私はかなりの問題を理解していなかったに続けることができました。 'pTest'の値は何ですか? – lucasnadalutti

+0

どのElementTreeを使用していますか? xml.etree.ElementTreeまたはlxml.etree? –

答えて

0

xml.etree.ElementTreeは標準ライブラリの一部であるため、私はあなたがxml.etree.ElementTreeを使用していることを前提としています。 pointsは、我々は次のポイントや検索を取得するために使用反復可能で、このスニペットでは

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(ルート)

次のスニペットを考えてみましょう。探しているノードを見つけたら(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> 

更新

あなたは、このノード、次のノード、および前のノードを変更したい場合は、イテラブルが戻ることができないため、以前のノードを追跡する必要があります。最も簡単な方法は、(listまたはcollections.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

'Monsieur'が入力の最後の項目である場合、これは未知の' StopIteration'を発生させるでしょう。 (通常の 'try' /' except'節を使用して)それをキャッチし、代わりにデバッグを容易にするために、より多くの例外的な例外(例えば、ValueError( "Monsieurの後に値がありません")) – Alfe

+0

良い点。また、* Mr *が処理しなければならないことがわかっていない場合もあります。 –

関連する問題