2016-08-17 12 views
1

要素ツリーを使用してこれらの項目エントリに要素を追加する最も簡単な方法を見つけようとしています。要素ツリーを既存のxmlに挿入する

以下のXML出力が(xmldata)に格納されています。これをファイルに書きたくないのですが、IDを追加するだけで、他のデータの対応するIDに関連付けることによってデータをさらに使用する必要があります。

あなたは、私は、リスト内のすべての項目に(すべてに同じidを)

 <id>555666</id> 

を追加したいちょうどその上で

 <archived type="bool">False</archived> 

を参照してください

 <?xml version="1.0" encoding="UTF-8" ?> 
      <root> 
       <tasks type="list"> 
        <item type="dict"> 
         <archived type="bool">False</archived> 
         <budget_spent type="float">0.0</budget_spent> 
         <billable_hours type="float">0.0</billable_hours> 
         <billable type="bool">True</billable> 
         <billable_amount type="float">0.0</billable_amount> 
         <budget_left type="null"/> 
         <over_budget_percentage type="null"/> 
         <task_id type="int">6356</task_id> 
         <detailed_report_url type="str">/reports/detailed/</detailed_report_url> 
         <name type="str">Planning</name> 
         <internal_cost type="float">0.0</internal_cost> 
         <budget type="null"/> 
         <budget_spent_percentage type="null"/> 
         <total_hours type="float">0.0</total_hours> 
         <over_budget type="null"/> 
         <billed_rate type="float">0.0</billed_rate> 
        </item> 
        <item type="dict"> 
         <archived type="bool">False</archived> 
         <budget_spent type="float">0.0</budget_spent> 
         <billable_hours type="float">0.0</billable_hours> 
         <billable type="bool">True</billable> 
         <billable_amount type="float">0.0</billable_amount> 
         <budget_left type="null"/> 
         <over_budget_percentage type="null"/> 
         <task_id type="int">6357</task_id> 
         <detailed_report_url type="str">/detailed/123</detailed_report_url> 
         <name type="str">Planning</name> 
         <internal_cost type="float">0.0</internal_cost> 
         <budget type="null"/> 
         <budget_spent_percentage type="null"/> 
         <total_hours type="float">0.0</total_hours> 
         <over_budget type="null"/> 
         <billed_rate type="float">0.0</billed_rate> 
        </item> 
       </tasks> 

*** *アップデート****

th私はこれを追加しました:

 tree = ET.fromstring(xmldata) 
    for item in tree.iterfind('tasks/item'): 
     idtag = ET.Element('id') 
     idtag.text = '555666' 
     item.insert(0, idtag) 

私は使用する更新されたデータがあります。このような

答えて

1

何かが、私はそれが...一つのことを働くかもしれないと思うあなたのアイデア

root = ET.fromstring(xmldata) 
for item in root.iterfind('tasks/item'): 
    idtag = ET.Element('id') 
    idtag.text = '555666' 
    item.insert(0, idtag) 
xmldata = ET.tostring(root, encoding="unicode") 
+0

を与える必要があります。私はファイルを使用していない...私は、ET.parse( 'ファイル名')の代わりに、私はツリー= ET.fromstring(xmldata)をやっているので、varaibleを使用しています。 (xmldata)に変更を書き込む方法はありますか?tree.write( 'modified.xml') –

+0

あなたのコメントを間違えて読みました。あなたはそのためにhttps://docs.python.org/3.5/library/xml.etree.elementtree.html#xml.etree.ElementTree.tostringを使用することができます – DAXaholic

+0

私は一度私の答えを調整します私は戻って - 現在AFK – DAXaholic

関連する問題