(PythonのElementTreeを使用して)完全に新しい要素をXMLファイルに追加するにはどうすればよいですか?

ペドロフィゲイレド

以下にコードを投稿しました。国「シンガポール」に新しい要素「大陸」を追加できます。しかし、完全な要素をXMLファイルに追加したいと思います。それは可能ですか?「data」変数には、XMLファイルに作成する要素のコンテンツが含まれています。私はそれを追加しようとしましたが...運がありません!

私のXMLファイル:

<data>
  <country name="Liechtenstein">
    <rank updated="yes">5</rank>
    <year>2008</year>
    <gdppc>141100</gdppc>
    <neighbor direction="E" name="Austria" />
    <neighbor direction="W" name="Switzerland" />
  </country>
  <country name="Singapore">
    <rank updated="yes">8</rank>
    <year>2011</year>
    <gdppc>59900</gdppc>
    <neighbor direction="N" name="Malaysia" />
  </country>
  <country name="Panama">
    <rank updated="yes">72</rank>
    <year>2011</year>
    <gdppc>13600</gdppc>
    <neighbor direction="W" name="Costa Rica" />
    <neighbor direction="E" name="Colombia" />
  </country>
</data>

これが私のPythonコードです:

import xml.etree.ElementTree as et


for item in root.findall("country"):
  if(item.get("name") == "Singapore"):
    new1 = et.Element("continent")
    new1.text = "Asia"
    item.append(new1)
tree.write("countries.xml")


data = '''
  <country name="Portugal">
    <rank updated="yes">21</rank>
    <year>2000</year>
    <gdppc>150000</gdppc>
    <neighbor direction="E" name="Spain" />
  </country>
'''

new2 = et.Element("country")
new2.text = data
root.append(new2)
tree.write("countries.xml")
mrxra

これを試して:

import xml.etree.ElementTree as et

xml = """
<data>
  <country name="Liechtenstein">
    <rank updated="yes">5</rank>
    <year>2008</year>
    <gdppc>141100</gdppc>
    <neighbor direction="E" name="Austria" />
    <neighbor direction="W" name="Switzerland" />
  </country>
  <country name="Singapore">
    <rank updated="yes">8</rank>
    <year>2011</year>
    <gdppc>59900</gdppc>
    <neighbor direction="N" name="Malaysia" />
  </country>
  <country name="Panama">
    <rank updated="yes">72</rank>
    <year>2011</year>
    <gdppc>13600</gdppc>
    <neighbor direction="W" name="Costa Rica" />
    <neighbor direction="E" name="Colombia" />
  </country>
</data>
"""

if __name__ == "__main__":
    tree = et.ElementTree(et.fromstring(xml))
    root = tree.getroot()

    data = '''
      <country name="Portugal">
        <rank updated="yes">21</rank>
        <year>2000</year>
        <gdppc>150000</gdppc>
        <neighbor direction="E" name="Spain" />
      </country>
    '''

    new2 = et.fromstring(data)
    root.append(new2)
    tree.write("countries2.xml")

重要なのはこの部分です。ここでは、xmlスニペット(データ)のxmlオブジェクト階層を生成し、それを子としてルートノードにアタッチします。

new2 = et.fromstring(data)
root.append(new2)

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ