更新元件值I有一个XML结构,其看起来类似于:使用xml.dom.minidom
<Store>
<foo>
<book>
<isbn>123456</isbn>
</book>
<title>XYZ</title>
<checkout>no</checkout>
</foo>
<bar>
<book>
<isbn>7890</isbn>
</book>
<title>XYZ2</title>
<checkout>yes</checkout>
</bar>
</Store>
使用xml.dom.minidom只(限制)我想
1)横移通过XML文件
2)搜索/获取特定元件,这取决于它的父
示例:作者1结帐元件,ISBN为author2
3)更改/设置元素的值
4)写新的XML结构到一个文件
谁能帮助吗?
谢谢!
UPDATE:
这是我做了什么至今
import xml.dom.minidom
checkout = "yes"
def getLoneChild(node, tagname):
assert ((node is not None) and (tagname is not None))
elem = node.getElementsByTagName(tagname)
if ((elem is None) or (len(elem) != 1)):
return None
return elem
def getLoneLeaf(node, tagname):
assert ((node is not None) and (tagname is not None))
elem = node.getElementsByTagName(tagname)
if ((elem is None) or (len(elem) != 1)):
return None
leaf = elem[0].firstChild
if (leaf is None):
return None
return leaf.data
def setcheckout(node, tagname):
assert ((node is not None) and (tagname is not None))
child = getLoneChild(node, 'foo')
Check = getLoneLeaf(child[0],'checkout')
Check = tagname
return Check
doc = xml.dom.minidom.parse('test.xml')
root = doc.getElementsByTagName('Store')[0]
output = setcheckout(root, checkout)
tmp_config = '/tmp/tmp_config.xml'
fw = open(tmp_config, 'w')
fw.write(doc.toxml())
fw.close()
你有什么,到目前为止,你在哪里遇到了问题? – 2010-03-23 19:33:53
是标签作者1,author2实际上是或作者的名字?你能它们定义为只是名称=“POE”的属性 – corn3lius 2010-03-23 19:34:43
@Tim?作者:我在这里添加的代码,我相信我不会写入文件的正确方法 @ corn3lius:我已编辑的作者名到“富”和“酒吧” 谢谢! – user291784 2010-03-23 21:17:14