<storage>
<record>
<values>
<points>99999999</points>
<points>Mr</points>
<points>Marvin</points>
<points>Homes</points>
<points>hardware</points>
<points>true</points>
<points>de</points>
<points>6</points>
<points>false</points>
</values>
</record>
</storage>
你好,
我正在尝试使用python(xml.etree.ElementTree)更改一些xml值。这只是xml数据的一小部分。
appelation=re.compile("Mr")
for fname in root.iter('points'):
if appelation.match(str(pTest)):
fname.text="New Mr/Mrs"
## here i am trying to edit the next iter (<points>Marvin</points>)
##fname.next().text="New name" -> doesnt work
任何建议如何解决下一个迭代?xml文件具有许多称为<“ points”>的标记,并且值始终是不同的。
我假设您正在使用,xml.etree.ElementTree
因为它是标准库的一部分。考虑以下代码段:
appelation = re.compile('Mr')
points = root.iter('points')
for node in points:
if appelation.match(node.text):
node.text = 'Monsieur'
node = next(points)
node.text = 'Francois'
break
ElementTree.dump(根目录)
在此代码段中,points
是一个可迭代的代码,我们将使用它来获取下一个要点并进行搜索。找到要查找的节点(Mr)后,我们可以对该节点和下一个节点进行操作(通过调用next
所述可迭代对象)。
输出:
<storage>
<record>
<values>
<points>99999999</points>
<points>Monsieur</points>
<points>Francois</points>
<points>Homes</points>
<points>hardware</points>
<points>true</points>
<points>de</points>
<points>6</points>
<points>false</points>
</values>
</record>
</storage>
如果要修改此节点,下一个节点和上一个节点,请执行以下操作:那么您需要跟踪先前的节点,因为无法迭代返回。最简单的方法是使用堆栈(alist
或collections.deque
will做):
appelation = re.compile('Mr')
points = root.iter('points')
nodes_stack = []
for node in points:
if appelation.match(node.text):
# Modify this node
node.text = 'Monsieur'
# Modify next node
next_node = next(points)
next_node.text = 'Francois'
# Modify previous node
previous_node = nodes_stack.pop()
previous_node.text = 'modified'
# Keep popping the stack the get to previous nodes
# in reversed order
ElementTree.dump(root)
break
else:
nodes_stack.append(node)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句