PythonでXMLを扱う(4)

Foundations of Python Network Programming

今回は、DOMインターフェースを使ってXML文書を作成してみる。DOMインターフェースなぞ使わなくても、プログラム言語の文字列操作でXML文書を作ることは可能ではあるが、DOMを用いることで正しいXML文書が簡単に作れるということが保証される。

—–



以下がDOMを使ってXMLを作る簡単な例である。

from xml.dom import minidom, Node
doc = minidom.Document()
doc.appendChild(doc.createComment("This is a XML document"))
country = doc.createElement('country')
doc.appendChild(country)
name = doc.createElement('name')
name.appendChild(doc.createTextNode('Japan'))
country.appendChild(name)
population = doc.createElement('population')
population.appendChild(doc.createTextNode('120,000,000'))
country.appendChild(population)
city = doc.createElement('city')
city.setAttribute('id', '1')
country.appendChild(city)
cityName = doc.createElement('name')
cityName.appendChild(doc.createTextNode('Tokyo'))
city.appendChild(cityName)
cityPopulation = doc.createElement('population')
cityPopulation.appendChild(doc.createTextNode('30,000,000'))
city.appendChild(cityPopulation)
print doc.toprettyxml(indent = '    ')

これを実行すると、以下のような出力がある。

<?xml version="1.0" ?>
<!--This is a XML document-->
<country>
<name>
Japan
</name>
<population>
120,000,000
</population>
<city id="1">
<name>
Tokyo
</name>
<population>
30,000,000
</population>
</city>
</country>

見事に綺麗なXMLが出力された。プログラムと結果を照らし合わせみれば、各行が何をやっているかは一目瞭然なので特に説明は書かない。