Personal tools
You are here: Home Downloads Tutorials Python XML Parsing in Python Using ElementTree
nrcfoss logo aukbc cdac iit mumbai iit madras ow2 iosn flosscc

XML Parsing in Python Using ElementTree

from elementtree.ElementTree import ElementTree , SubElement

Here is an xml  parsing and replace program for its body  tag contents.


import sys

from  elementtree.ElementTree  import ElementTree,                                                                                      SubElement



doc = ElementTree(file = "sample.xml")

# find the body element by tag name

body = doc.getroot().findall("body")[0]

# Remove all child elements, text(and attributes)


body.clear( )


# Insert new lead text

body.text  =  "This is  a new memo. Send responses to \n"

new_element = SubElement(body,  'a', {'href':                                                                         ''})

new_element.text = ""

new_element.tail = "\nThanks. \n"

# write  out  the modified XML

memoxml = open ("/root/Desktop/memo.xml", "w")




Document Actions