我有一个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()
我不太清楚你说的“结帐”是什么意思。此脚本将找到元素并更改该元素的值。也许你可以根据自己的具体需要来调整它。
一般的想法是,将作者的名字与“Store”元素的子标记名相匹配,然后通过作者的子标记名递归,寻找与目标元素标记名的匹配。在这个解决方案中有很多假设,但它可能会让你开始。尝试在不使用递归的情况下处理XML这样的层次结构是很痛苦的。
干杯, 菲尔
回想起来,“alterElement”函数中有一个错误。我已经修复了这个(注意“found”变量)
相关问题 更多 >
编程相关推荐