6

したがって、基本的には、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 と結婚していませんが、スキーマを作成する必要はありません。アドバイス/解決策をよろしくお願いします!

4

2 に答える 2

7

私の意見では、これElementTreeは良い選択です。将来、もう少し機能の高いパッケージが必要な場合lxmlは、同じインターフェースを使用するサードパーティ モジュールに切り替えることができます。

あなたの問題に対する答えは、ドキュメントhttp://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.writeにあります。

出力は、文字列 (str) またはバイナリ (バイト) のいずれかです。これは encoding 引数によって制御されます。エンコーディングが「unicode」の場合、出力は文字列です。それ以外の場合はバイナリです。開いているファイル オブジェクトの場合、これはファイルの種類と競合する可能性があることに注意してください。文字列をバイナリ ストリームに書き込もうとしたり、その逆を行ったりしないように注意してください。

基本的に、あなたはそれを正しくやっています。ファイルをopen()テキストモードで使用すると、ファイルは文字列を受け入れ、. の'unicode'引数を使用する必要がありますtree.write()。それ以外の場合は、ファイルをバイナリ モード ( にエンコーディング引数なしopen()) で開き、 で を使用'utf-8'できますtree.write()

単独で動作する少しクリーンアップされたコード:

#!python3
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

root = et.Element('AllItems')     # create the element first...
tree = et.ElementTree(root)       # and pass it to the created tree

root.append(dict_to_elem(  {'some_tag':'Hello World', 'xxx': 'yyy'}  ))
# Lather, rinse, repeat this append step as needed

filename = 'a.xml'
with open(filename, 'w', encoding='utf-8') as file:
    tree.write(file, encoding='unicode')

# The alternative is...    
fname = 'b.xml'
with open(fname, 'wb') as f:
    tree.write(f, encoding='utf-8')

目的によります。2 つのうち、私は個人的に最初のソリューションを好みます。テキスト ファイルを作成することが明確に示されています (そして、XML はテキスト ファイルです)。

ただし、エンコーディングを指定する必要がない最も簡単な方法は、次のtree.writeようにファイル名を渡すことです。

tree.write('c.xml', encoding='utf-8')

ファイルを開き、指定されたエンコーディング(以下の Sebastian のコメントの後に更新)を使用してコンテンツを書き込み、ファイルを閉じます。そして、あなたはそれを簡単に読むことができ、ここで間違いを犯すことはありません.

于 2012-12-13T08:45:12.427 に答える