简体   繁体   中英

Python - search and replace content in XML file

I have a requirement where I have a sample XML file with a well defined structure. I want to search of a tag/child in XML file, replace its text/value with some input file and save the changes to a new XML file preferably without effecting the input sample XML.

I understand this can be achieved by a XML parser to traverse through to the child as intended. But problem is that at the top of my XML file I have something like this

<nc:data xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0">

I have written a python function as shown below to do it but I am failing to get the intended thing.

def search_replace():
    replicate()        // This function just makes a tmp file from sample input XML to work on. 
    tree = et.parse("/path/to/file/tmp_file.xml")
    tree.find('nc:data/child1/child2/child3').text = 'test'
    tree.write("new_file.xml")

Please suggest what would be best approach to handle this. I am not very python-skilled as of now !!

You need to create dictionary that map the prefix to namespace uri and pass that as additional parameter of find() :

def search_replace():
    replicate()
    tree = et.parse("/path/to/file/tmp_file.xml")
    nsmap = {'nc': 'urn:ietf:params:xml:ns:netconf:base:1.0'}
    tree.find('nc:data/child1/child2/child3', nsmap).text = 'test'
    tree.write("new_file.xml")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM