forked from roytuts/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxml_modifier.py
More file actions
32 lines (28 loc) · 930 Bytes
/
xml_modifier.py
File metadata and controls
32 lines (28 loc) · 930 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import xml.etree.ElementTree as ET
#pretty print method
def indent(elem, level=0):
i = "\n" + level*" "
j = "\n" + (level-1)*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for subelem in elem:
indent(subelem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = j
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = j
return elem
tree = ET.parse('bookstore2.xml')
root = tree.getroot()
#update all price
for price in root.iter('price')
34C5
:
new_price = int(price.text) + 5
price.text = str(new_price)
price.set('updated', 'yes')
#write to file
tree = ET.ElementTree(indent(root))
tree.write('bookstore2.xml', xml_declaration=True, encoding='utf-8')