Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 创建不同版本的XML文件时,仅编辑和更新XML文件中的数字文本_Python_Xml_Elementtree_Itertools - Fatal编程技术网

Python 创建不同版本的XML文件时,仅编辑和更新XML文件中的数字文本

Python 创建不同版本的XML文件时,仅编辑和更新XML文件中的数字文本,python,xml,elementtree,itertools,Python,Xml,Elementtree,Itertools,我正在尝试对xml文件进行可变性研究。下面显示了一个psuedo代码示例 <data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <currency>1.21$/kg</currency> <gdppc>141100</gdppc> <neighbor name="Austria" d

我正在尝试对xml文件进行可变性研究。下面显示了一个psuedo代码示例

<data>
<country name="Liechtenstein">
    <rank updated="yes">2</rank>
    <currency>1.21$/kg</currency> 
    <gdppc>141100</gdppc>
    <neighbor name="Austria" direction="E"/>
    <neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
    <rank updated="yes">5</rank>
    <currency>4.1$/kg</currency> 
    <gdppc>59900</gdppc>
    <neighbor name="Malaysia" direction="N"/>
</country>

欢迎所有建议。谢谢

在我看来,您需要遍历树才能做到这一点。原因是您需要实际更新XML元素的文本,以便输出正确

要遍历etree的节点,需要使用Element.getchildren()。这将返回此元素的所有子元素的列表。因为一个英文描述非常粗糙,所以我要开始编写代码

def traversal(elem):
    text = elem.text
    # do work here

    for node in elem.getchildren():
        traversal(node)
这是一个非常经典的树遍历递归解决方案,您可以一个节点一个节点地遍历,执行工作并访问所有子节点。最终,你会去拜访他们。请注意,此解决方案需要将XML数据放入内存中,但似乎您已经加载了它,所以您在这里应该状态良好

我还应该谈谈为了进行文本匹配,您需要做些什么。如果您的条件像“所有数字”一样简单,我建议使用正则表达式。我希望下面的内容足以让您开始学习

import re
digitsRegex = re.compile(r'\d+$')
digitsRegex.match('12345')
import re
digitsRegex = re.compile(r'\d+$')
digitsRegex.match('12345')