【发布时间】:2016-12-15 08:28:36
【问题描述】:
我有一个值列表(比如一个 txt 文件),我需要在一个 XML 文件中找到这些值,并将这些值替换为在另一个 txt 文件中找到的等效新值。我所管理的是逐行读取xml并替换:
for line in open(template_file_name,'r'):
output_line = line
output_line = string.replace(output_line, placeholder, value)
print output_line
看看如何以更有效的方式实现这一目标,
下面是我将使用的 XML:
<?xml version="1.0"?>
<sample>
<a>
<id>Value_to_search_for</id>
<class />
<gender />
</a>
</sample>
我想编写一个 Python 脚本来搜索标签“id”并将值“Value_to_search_for”替换为“Replacement_value”。
但是,上述 XML 的嵌套可以更改。所以我想制作一个通用脚本,它将独立于其确切位置搜索标签“id”。
【问题讨论】:
-
您是否会考虑使用 xml 解析器,例如 lxml.ElementTree?
-
是的,我试过了,但我无法摆脱我专门提供路径的部分。所以我需要一些东西,那将是誓言不可知的
标签: python xml string python-2.7 python-3.x