【问题标题】:python search and replace xml file, ignoring the node the tag existspython搜索替换xml文件,忽略标签存在的节点
【发布时间】: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


【解决方案1】:
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')

【讨论】:

  • 上面看起来更接近我尝试做的事情,可能有 xml 文件作为参数,以及要搜索和替换的值
  • @Toled 你的意思是函数的参数?请检查更新的答案。
  • 完全正确,并且在两个 txt 文件 filea.txt、fileb.txt 中也有 Value_to_search_for 和 Replacement_value,用于以每行为基础的 Value_to_search_for 和 Replacement_value
【解决方案2】:

这样的事情怎么样:

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' 中查找值的开头和结尾的索引,并将其中的内容替换为您的新值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    • 2013-01-10
    • 2011-01-06
    • 2015-12-03
    相关资源
    最近更新 更多