How to search and replace text in an XML file using Python?

后端 未结 1 927
长情又很酷
长情又很酷 2021-02-09 20:07

How do I search an entire xml file for a specific text pattern and then replace each occurrence of that text with new text pattern in Python 3.5?

Ever

1条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-09 20:36

    Caveats:

    • I have never worked with the xml.etree.ElementTree library
    • I have never worked with it because I never find myself manipulating XML
    • I don't know if this is the "best" way compared to someone that knows the library in and out
    • Commentors seem set on judging you instead of helping you out

    This is a modification from this excellent answer. The thing is, you need to read the XML file in and parse it.

    import xml.etree.ElementTree as ET
    
    with open('xmlfile.xml', encoding='latin-1') 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='latin-1')
    

    Note that you can change the encoding parameter to something else such as: utf-8, cp1252, ISO-8859-1, etc. Really depends on your system and file.

    0 讨论(0)
提交回复
热议问题