したがって、基本的には、Python 辞書のデータから生成された要素を使用して XML を生成したいと考えています。ここで、タグになるのは辞書のキーであり、テキストは辞書の値です。アイテムに属性を与える必要はありません。目的の出力は次のようになります。
<AllItems>
<Item>
<some_tag> Hello World </some_tag>
...
<another_tag />
</Item>
<Item> ... </Item>
...
</AllItems>
xml.etree.ElementTree パッケージを使用して、ツリーを作成し、次のように要素「AllItems」をルートとして設定してみました。
from xml.etree import ElementTree as et
def dict_to_elem(dictionary):
item = et.Element('Item')
for key in dictionary:
field = et.Element(key.replace(' ',''))
field.text = dictionary[key]
item.append(field)
return item
newtree = et.ElementTree()
root = et.Element('AllItems')
newtree._setroot(root)
root.append(dict_to_elem( {'some_tag':'Hello World', ...} )
# Lather, rinse, repeat this append step as needed
with open( filename , 'w', encoding='utf-8') as file:
tree.write(file, encoding='unicode')
最後の 2 行で、open() ステートメントのエンコーディングを省略し、write() メソッドのエンコーディングを省略して 'UTF-8' に変更しようとしましたが、"') は str 型であるというエラーが発生します。シリアル化できません
だから私の問題-私が知りたいのは、上記の形式でUTF-8 XMLを最初から作成する方法と、UTF-8を適切に処理できるようにする別のパッケージを使用したより堅牢なソリューションがあるかどうかだけです文字?私はソリューションのために ElementTree と結婚していませんが、スキーマを作成する必要はありません。アドバイス/解決策をよろしくお願いします!