libxml2 を python で使ってXMLドキュメントを更新する方法のメモを残す.

xpath でノードを指定し,取得したノードの値を変更したり,削除したり,その下にノードを追加したりする.

まず
<?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 attr="123">some sample text</is:child-tag>
<is:child-tag attr="59"/>
</is:root-tag>

という XML ドキュメントを想定する.


import libxml2
doc=libxml2.parseDoc('<is:root-tag xmlns:is="http://www.physiome.jp/ns/insilicoml"><is:child-tag>content text</is:child-tag><is:child-tag attr="123">some sample text</is:child-tag><is:child-tag attr="59"/></is:root-tag>')


attr="123" という child-tag の値('some sample text')を別の値に置き換えることを考える.

# まず,そのノードを xpath を使ってみつける
ctx=doc.xpathNewContext()
ctx.xpathRegisterNs('is','http://www.physiome.jp/ns/insilicoml')
nodes=ctx.xpathEvalExpression('/is:root-tag/is:child-tag[@attr="123"]')

node = nodes[0]

# そのノードの内容を上書きする.
node.setContent('new text comments')

# また,attribute の値を変更するには,
node.setProp('attr','999')

# attribute を削除するには
node.unsetProt('attr')

# このノードの下に新しいノードを追加するには
node.newChild(ns, 'grand-child', 'some text')

# とすればいいが,ns は name space を意味しており,
# これを取得するには,
root = doc.getRootElement()
ns = root.ns()

# 新たに name space を定義するなら,
newns = root.newNs('http://xxx', 'ix')


# ノードを削除するには
node.unlinkNode()
node.freeNode()

(freeNode() しなければ,nodes[0]にはまだそのノードの情報が入っている.
しかし,doc からは削除されている)




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