Search and replace multiple lines in xml/text files using python

后端 未结 3 873
萌比男神i
萌比男神i 2020-12-18 08:31

---Update 3: I have got the script to update the required data into the xml files completed but the following code is being dropped from the written file. Why is this? how c

相关标签:
3条回答
  • 2020-12-18 08:41

    Using the given tag(s) above:

    import os
    import xml
    from xml.etree import ElementTree as et 
    path = r"/your/path/to/xml.file" 
    tree = et.parse(path)
    for node in tree.findall('.//northbc'):
        node.text = "New Value"
    tree.write(path)
    

    Here, XPATH .//northbc returns all the 'northbc' nodes in the XML doc. You can tailor the code for your need easily.

    0 讨论(0)
  • 2020-12-18 08:42

    If you're dealing with valid XML, use XPath to find the nodes of interest and the ElementTree api to manipulate the node.

    For instance, your xpath might be something like '//northbc' and you would just replace the text node inside it.

    See http://docs.python.org/library/xml.etree.elementtree.html as well as http://pypi.python.org/pypi/lxml/2.2.8 for two different libraries that will help you get this done. Search google for XPath and see the w3c tutorial for a decent intro to XPath (I apparently can't post more than two links in a post or I'd link it too)

    0 讨论(0)
  • 2020-12-18 08:58

    I might be stating the obvious here, but did you consider using a DOM tree to parse and manipulate your XML?

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