libxml2 の python バインディングのメモ

doc のルートノードを取得する.

root = doc.getRootElement()


ルートノードのタグの名前を取得する.

tag = root.name


あるタグの下に文字列として書かれたタグリストを要素として追加する.
例えば,'<is:module xmlns:is="http://www.physiome.jp"><is:name>any model</is:name></is:module>' というようなXMLテキストをタグとして追加したい事がある.
この用途に

node.newChild(None, '', '<tag_a>hello</tag_a>')

は使えない.これを使うと

<>&lt;tag_a&gt;hello&lt;/tag_a&gt;</>

というように挿入される.

次のようにすると上記のことが実行できる.

doc2 = libxml2.parseDoc('<tag_a>hello</tag_a>')
root2 = doc2.getRootElement()
node.addChild(root2)



いろいろ試してみてわかったが,
一つの事を行うのに複数のやり方があるようだ.

例えば,ある node の下に child node を追加するにしても,

newnode = node.newChild(ns, 'tag', 'value')
newnode.setProp('attr1', '123')

としてもいいし,

newnode = libxml2.newNode('is:tag')
newnode.setContent('value')
newnode.newProp('attr1', '123')
node.addNode(newnode)

としてもよい.


# あるノードの XPath を取得する

node.nodePath()


# あるノードの copy を作る
<is:tag att="12"><is:child>hello</is:child></is:tag>
という内容が, node にセットされているとする.

new_node = node.copyNode(0)
print new_node
<tag/>


new_node = node.copyNode(1)
print new_node
<is:tag xmlns:is="http://xxx" att="12"><is:child>hello</is:child></is:tag>


new_node = node.copyNode(2)
print new_node
<is:tag xmlns:is="http://xxx" att="12"/>



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