libxml2 を python で使う方法のメモ

新しいXMLドキュメントを libxml2 を使って作ります.


import libxml2

# 空のドキュメントを作成
doc = libxml2.newDoc('1.0')

# root タグを作成する
root=doc.newChild(None, 'root-tag', None)

# ドキュメントを確認してみる
print doc

<?xml version="1.0"?>
<root-tag/>



# name space を設定する
ns=root.newNs('http://www.physiome.jp/ns/insilicoml','is')
root.setNs(ns)

<?xml version="1.0"?>
<is:root-tag xmlns:is="http://www.physiome.jp/ns/insilicoml"/>



# child node を root-tag の下に追加する
root.newChild(ns, 'child-tag', 'content text')

<?xml version="1.0"?>
<is:root-tag xmlns:is="http://www.physiome.jp/ns/insilicoml">
<is:child-tag>content text</is:child-tag>
</is:root-tag>



# child node に attribute もセットする
child=root.newChild(ns,'child-tag','some sample text')
child.setProp('attrib','123')

<?xml version="1.0"?>
<is:root-tag xmlns:is="http://www.physiome.jp/ns/insilicoml">
<is:child-tag>content text</is:child-tag>
<is:child-tag attrib1="123">some sample text</is:child-tag>
</is:root-tag>




やじるし libxml2 + Python メモの目次