Python search and replace in an xml file



I have an xml called sample.xml. I use minidom to read and parse that xml file. Here is the content of the xml file which I am mostly concerned about:-



<sub>-s ${student.name} -e '${student.subject}' -c junior</sub>


The python script student.py requires two command line arguments to run.


I want to replace whats between -s ${student.name} -e by the first argument which I provide and I want to replace what is between -e '${student.subject}' -c by the second argument I provide to run the script.


Here is my code snippet:-



from xml.dom import minidom
import sys
import re
import commands
from optparse import OptionParser
parser.add_option("-e", "--student",
action="store",
dest="student",
type="str",
help="student name")
parser.add_option("-s", "--subject",
action="store",
dest="subject",
type="str",
help="Subject name")
StudentXML = minidom.parse("sample.xml")
class = StudenXML.getElementsByTagName("class")
for stu in class:
name = stu.getElementsByTagName("sub")[0]
getName = stu.childNodes[0]
details = Name.data
if "-s" in details:
#replace ${student.name} by sam
if "-e" in details:
# replace ${student.subject} by chemistry


This is the format to run the script:-



python student.py -e sam -s chemistry

No comments:

Post a Comment