Hướng dẫn replace text in xml python - thay thế văn bản trong xml python

Làm cách nào để tìm kiếm toàn bộ tệp XML cho một mẫu văn bản cụ thể và sau đó thay thế từng lần xuất hiện của văn bản đó bằng mẫu văn bản mới trong Python 3.5?xml file for a specific text pattern and then replace each occurrence of that text with new text pattern in Python 3.5?

Mọi thứ khác (định dạng, thuộc tính, nhận xét, v.v.) cần phải duy trì như trong tệp XML gốc.

Tôi đang chạy Python 3.5.1 trên Windows (Win32).

Cụ thể, tôi muốn thay thế từng lần xuất hiện "tên tính năng" bằng "hoạt động này" và thay thế từng lần xuất hiện "số tính năng" bằng "12345".

Tôi đã cố gắng học Python và xml.etree.elementtree nhưng không thể tìm ra điều này. Tôi đã xem "Tìm kiếm và thay thế một dòng trong tệp .xml trong Python", "Tìm kiếm và thay thế một dòng trong một tệp trong Python" và "Cách tìm kiếm và thay thế văn bản trong một tệp bằng Python?" Và các Q/A hiện có khác trên trang web này nhưng không thể tìm ra điều này - Tôi không phải là một lập trình viên có kinh nghiệm, vì vậy xin vui lòng cho tôi biết nếu cần thêm đầu vào. Giúp đỡ của bạn được đánh giá rất cao!!!

Dưới đây là một bản sao của mã XML trông như thế nào khi tôi mở nó trong Notepad (ngoại trừ tôi đã thêm khoảng trống để thụt lên từng dòng và nhấn trả lại cho một số dòng khi tôi dán nó vào câu hỏi này):


    
        
            
                FID FEATURE NUMBER
            
            
                FEATURE NAME
            
            
                Common features
                FID FEATURE NUMBER
            
        
    
    FEATURE NUMBER - FEATURE NAME
    
        
        REVIEWERS: I guessed at the FEATURE NAME
        
            This feature applies to the following platforms: FEATURE NAME
    
    
        
        
            REVIEWERS: What do we put here? See template (link given in review email) for more information.
        
    
    
        
        
        
            
            What FEATURE NAME do we put here?
        
        
            
            What FEATURE NAME do we put here?
            This feature applies to the following: FEATURE NUMBER and text.
        
        
            
            What FEATURE NAME do we put here?
        
    
    
        
        REVIEWERS: What FEATURE NUMBER do we put here?
        
            
        
    

Đây là mã mới nhất tôi đang cố gắng làm việc:

from xml.etree import ElementTree as et
tree = et.parse('Atemplate2.xml')
tree.find('description-topic/access-info/index-term-set/index-term/primary/').text = '12345'
tree.write('Atemplate2.xml')

Tôi nhận được lỗi sau: Traceback (cuộc gọi gần đây nhất) ') .Text =' 12345 '

Thuộc tínhError: đối tượng 'nonetype' không có thuộc tính 'văn bản'

Tôi muốn có thể tìm kiếm và sửa đổi bất kỳ lần xuất hiện nào trong toàn bộ tệp, nhưng tôi không thể tìm ra cách để có được một lần xuất hiện cụ thể của văn bản mà tôi đang tìm kiếm.

Đây là mã tôi đã cố gắng sử dụng để tìm đường dẫn:

import xml.etree.ElementTree as ET
tree = ET.parse('Atemplate.xml')
root = tree.getroot()

print(root.tag, root.attrib, root.text)

for child in root:
    print(child.tag, child.attrib, child.text)
for label in root.iter('label'):
    print(label.tag, label.attrib, label.text)
for title in root.iter('title'):
    print(title.attrib)

Tôi cũng đã thử mã sau:

with open('Atemplate2.xml') as f:
    tree = ET.parse(f)
    root = tree.getroot()

for elem in root.getiterator():
    try:
        elem.text = elem.text.replace('FEATURE NAME', 'THIS WORKED')
        elem.text = elem.text.replace('FEATURE NUMBER', '12345')
    except AttributeError:
        pass

tree.write('output.xml')

Nhưng điều đó gây ra lỗi sau:

File "", line 2, in 
    tree = ET.parse(f)
File "C:\MyPath\Python35-32\lib\xml\etree\ElementTree.py", line 1182, in parse
    tree.parse(source, parser)
File "C:\ MyPath \Python35-32\lib\xml\etree\ElementTree.py", line 594, in parse
    self._root = parser._parse_whole(source)
File "C:\ MyPath \Python35-32\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]

UnicodedEcodeError: codec 'Charmap' không thể giải mã byte 0x9d ở vị trí 1119: Bản đồ ký tự để

# #

Cập nhật cuối cùng - Đây là mã hoạt động cho tôi cuối cùng (cảm ơn bạn, Jarad!):

import lxml.etree as ET
#using lxml instead of xml preserved the comments

#adding the encoding when the file is opened and written is needed to avoid a charmap error
with open('filename.xml', encoding="utf8") as f:
  tree = ET.parse(f)
  root = tree.getroot()


  for elem in root.getiterator():
    try:
      elem.text = elem.text.replace('FEATURE NAME', 'THIS WORKED')
      elem.text = elem.text.replace('FEATURE NUMBER', '123456')
    except AttributeError:
      pass

#tree.write('output.xml', encoding="utf8")
# Adding the xml_declaration and method helped keep the header info at the top of the file.
tree.write('output.xml', xml_declaration=True, method='xml', encoding="utf8")