【发布时间】:2010-03-23 18:55:00
【问题描述】:
我有一个类似于以下内容的 XML 结构:
<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) 搜索/获取特定元素,具体取决于其父元素
示例:author1 的 checkout 元素,author2 的 isbn
3)更改/设置该元素的值
4)将新的 XML 结构写入文件
有人可以帮忙吗?
谢谢!
更新:
这就是我到目前为止所做的事情
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()
【问题讨论】:
-
到目前为止你有什么,你在哪里遇到问题?
-
标签是作者1、作者2,还是作者的名字?您可以将它们定义为具有 name="poe" 属性的作者吗?
-
@Tim:我在这里添加了代码。我确定我没有以正确的方式写入文件。 @corn3lius:我已将作者姓名编辑为“foo”和“bar”谢谢!