# -*- coding: utf-8 -*- import xml.dom.minidom s = '<?xml version="1.0"?>\ <parent id="top">\ <child name="paul">Text goes here</child>\ <child name="fred">More text</child>\ </parent>' def print_parent(emt): tup = (emt.tagName, emt.getAttribute("id")) print "['%s', {'id': '%s'}]" % tup def print_child(emt): tup = (emt.tagName, emt.getAttribute("name"), emt.childNodes[0].data) print "['%s', {'name': '%s'}, '%s']" % tup # 文字列からdomオブジェクトを生成 dom = xml.dom.minidom.parseString(s) # ファイルからdomオブジェクトを生成する場合 # dom = xml.dom.minidom.parse("file.xml") # dom から要素を取得する parent_emt = dom.getElementsByTagName("parent")[0] child_emt_list = parent_emt.getElementsByTagName("child") # プリントする print_parent(parent_emt) for child_emt in child_emt_list: print_child(child_emt) # parent_emt に要素を追加する new_emt = dom.createElement("child") new_emt.setAttribute("name", "yoshi") new_emt.appendChild(dom.createTextNode("hello")) parent_emt.appendChild(new_emt) # DOMオブジェクトを文字列にする ds = dom.toprettyxml(" ") print print ds # DOMオブジェクトをファイルに保存する with open("xml-file.xml", "w") as f: dom.writexml(f, "", "\t", "\n")
実行すると
['parent', {'id': 'top'}]
['child', {'name': 'paul'}, 'Text goes here']
['child', {'name': 'fred'}, 'More text']
<?xml version="1.0" ?>
<parent id="top">
<child name="paul">
Text goes here
</child>
<child name="fred">
More text
</child>
<child name="yoshi">
hello
</child>
</parent>
詳細はドキュメントで
0 件のコメント:
コメントを投稿