python搜索并替换xml文件,忽略标记存在的节点

2024-03-29 04:45:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个值列表(比如一个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\u to\u search\u for”替换为“Replacement\u value”。你知道吗

但是,上述XML的嵌套可以更改。所以我想做一个通用的脚本,它将独立于标签的确切位置来搜索标签'id'。你知道吗


Tags: 文件tosampletxt脚本id列表for
2条回答
from lxml import etree as et


def replace_tag_text_from_xml_file(xml_file_path,xpath,search_str,replacement_str):
    root = et.parse(xml_file_path)

    id_els = root.iterfind(xpath)

    for id_el in id_els:
        id_el.text = id_el.text.replace(search_str, replacement_str)

    return et.tostring(root)


print replace_tag_text_from_xml_file('./test.xml', './/id', 'Value_to_search_for', 'Replacement_value')

这样怎么样:

placeholder = "Value_to_search_for"
new_value = "New_Value"


for line in open("yourfile.xml"):
    output_line = line

    if "<id>" in line:
        beginning_index = line.index("<id>")
        end_index = line.index("</id>")+5       # 5 = The number of characters in '</id>'
        output_line = line
        output_line = output_line[beginning_index:end_index].replace(placeholder, new_value)

    print (output_line)

它在标记“id”中查找值的开头和结尾的索引,并用新值替换其中的内容。你知道吗

相关问题 更多 >