簡體   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