import sys, xml.etree.ElementTree as ET # Create the root of the ElementTree from file root = ET.parse("thefile").getroot() # Get an iterator for the root node iterator = root.getiterator("Item") # Loop using the iterator # (Please use clear variable names!) for item in iterator: # To find a sub-element with a text tag, use find() old_symbol = item.find("Symbol") # This is how you get its text field text = old_symbol.text # Is 'UPS' in our text field? if 'UPS' in text: # If so, remove the sub-element # remove() takes out nodes, not text item.remove(old_symbol) # Add a new sub-element to the item new_symbol = ET.SubElement(item, "Symbol") # Set its text field to the appropriate thing new_symbol.text = text[0:3]+"2009" # Now get the full tree from the root tree = ET.ElementTree(root) # And write to file! tree.write("out.xml")
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question