Wednesday, 4 September 2013

Replacing a text node by another in xml using python

Replacing a text node by another in xml using python

this is my xml file:
<?xml version="1.0" encoding="UTF-8" ?>
<raml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="raml21.xsd">
<cmData type="actual" scope="all" name="plan_file">
<header>
<log dateTime="2011-05-18T04:05:02" action="created" />
</header>
<managedObject class="Fruit">
<p name="Apple">100</p>
<p name="Mango">4</p>
<p name="Pear">99</p>
<p name="Jackfruit">67</p>
<p name="Strawberry">200</p>
<p name="Guava">100</p>
<p name="Banana">100</p>
<p name="Breadfruit">1500</p>
<p name="Musambi">100</p>
</managedObject>
</cmData>
</raml>
What i need to do is that. i need to replace the text nodes(100,4,99) of a
given attribute with another number(entered through the python shell
during run-time).i need to change only one text node at a time(which is
also entered through the shell). i need a seperate xml file with the
changed value.
i wrote the python script which goes like this:
from xml.dom import minidom
import os.path
def new_value(parameter, parameter_value, target_dir, inputfile):
count = len(open(inputfile).readlines())
dom = minidom.parse(inputfile)
name = dom.getElementsByTagName('p')
inFile = open(inputfile,'r')
fullname = os.path.join(target_dir, "test" + str(parameter_value) +
".xml")
outFile = open(fullname,'w')
for i in range(count):
content = inFile.readline()
matchobj = re.search(parameter, content)
if(matchobj):
newcontent = content.replace(name[2].firstChild.nodeValue,
str(parameter_value))
outFile.write(newcontent)
else:
outFile.write(content)
outFile.close()
parameter = input("Enter the parameter: ")
target_dir = input("Enter the target directory: ")
input_file = input("Enter the input file: ")
parameter_value = input("Enter the value to replace: ")
new_value(parameter, parameter_value, target_dir, input_file)
here since i am using the expression,
newcontent = content.replace(name[2].firstChild.nodeValue,
str(parameter_value))
this script is running but using this(since i am using name[2]), i can
change only the index 2 of the xml file,ie, Pear.if i write 1 instead of
2, i am able to change the value of Mango and so on. but i need to make
the script general. how can i modify the script for that???
Thanks for ur help.. :)

No comments:

Post a Comment