繁体   English   中英

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

[英]python search and replace xml file, ignoring the node the tag exists

我有一个值列表(比如一个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'。

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'中找到值的开头和结尾的索引,并用新值替换内部的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM