0

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 !!

har07
  • 88,338
  • 12
  • 84
  • 137
AB2328
  • 79
  • 2
  • 10
  • what is `et` exactly, `xml.etree.ElementTree`? – har07 Jul 23 '15 at 13:04
  • Sorry I dint put that.. from xml.etree import ElementTree as et – AB2328 Jul 23 '15 at 13:18
  • possible duplicate of [Parsing XML with namespace in Python via 'ElementTree'](http://stackoverflow.com/questions/14853243/parsing-xml-with-namespace-in-python-via-elementtree) – har07 Jul 23 '15 at 13:37
  • Not actually !! The link that you have provided speaks of tags with same namespace. My problem is that I have only one namespace but I am unable to traverse through it as it has colon(:) in its name. – AB2328 Jul 23 '15 at 14:50
  • @har07, I have changed the program and modified it to use lxml. I am pretty much successful but still not complete with it. I want to know how can I get the value attached to a particular tag in xml file. Please share any examples if you have to search and replace in xml file by finding tag in the file. for eg. "abc", here if one can search for 'a' and replace abc inside it – AB2328 Jul 24 '15 at 09:40
  • Then please update your question with the latest code, and explain what you're trying to achieve now – har07 Jul 24 '15 at 09:47

1 Answers1

0

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")
har07
  • 88,338
  • 12
  • 84
  • 137