PythonでXMLを触ってみる2 minidomね
つづいて新規にXMLを作成してみます。
minidom2.py
# _*_ coding:UTF-8 _*_ import xml.dom.minidom, codecs doc = xml.dom.minidom.Document() root = doc.createElement('cars') doc.appendChild(root) car = doc.createElement('car') root.appendChild(car) name = doc.createElement('name') car.appendChild(name) price = doc.createElement('price') car.appendChild(price) name.appendChild(doc.createTextNode(u'乗用車')) price.appendChild(doc.createTextNode('150')) f1 = codecs.open('Sample3.xml', 'w', 'utf-8') doc.writexml(f1) f1.close()
ここではcar Elementをひとつ追加してみます。
実行結果
$ python minidom2.py $ cat Sample3.xml <?xml version="1.0" ?><cars><car><name>乗用車</name><price>150</price></car></cars>
1行で出力されてしまいました。
少し改良してみます。
minidom2.py
# _*_ coding:UTF-8 _*_ import xml.dom.minidom doc = xml.dom.minidom.Document() root = doc.createElement('cars') doc.appendChild(root) car = doc.createElement('car') root.appendChild(car) name = doc.createElement('name') car.appendChild(name) price = doc.createElement('price') car.appendChild(price) name.appendChild(doc.createTextNode(u'乗用車')) price.appendChild(doc.createTextNode('150')) f1 = open('Sample3.xml', 'w') f1.write(doc.toprettyxml(' ', '\n', 'utf-8')) f1.close()
writexmlではなくtoprettyxmlで文字列として出力してファイルに書き出します。
この場合はエンコードを指定できるのでcodecsのopenではなく
ビルトインのopenを使用しています。
toprettyxmlの第1引数はスペース2個としています。
実行結果
$ python minidom2.py $ cat Sample3.xml <?xml version="1.0" encoding="utf-8"?> <cars> <car> <name> 乗用車 </name> <price> 150 </price> </car> </cars>