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)
私は使用する更新されたデータがあります。このような
を与える必要があります。私はファイルを使用していない...私は、ET.parse( 'ファイル名')の代わりに、私はツリー= ET.fromstring(xmldata)をやっているので、varaibleを使用しています。 (xmldata)に変更を書き込む方法はありますか?tree.write( 'modified.xml') –
あなたのコメントを間違えて読みました。あなたはそのためにhttps://docs.python.org/3.5/library/xml.etree.elementtree.html#xml.etree.ElementTree.tostringを使用することができます – DAXaholic
私は一度私の答えを調整します私は戻って - 現在AFK – DAXaholic