Skip to content

Commit 72d151d

Browse files
authored
Add files via upload
1 parent 639dd91 commit 72d151d

2 files changed

Lines changed: 52 additions & 0 deletions

File tree

python-xml-builder/readme.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
You can read tutorial https://www.roytuts.com/building-xml-using-python/

python-xml-builder/xml_builder.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import xml.etree.ElementTree as ET
2+
3+
#pretty print method
4+
def indent(elem, level=0):
5+
i = "\n" + level*" "
6+
j = "\n" + (level-1)*" "
7+
if len(elem):
8+
if not elem.text or not elem.text.strip():
9+
elem.text = i + " "
10+
if not elem.tail or not elem.tail.strip():
11+
elem.tail = i
12+
for subelem in elem:
13+
indent(subelem, level+1)
14+
if not elem.tail or not elem.tail.strip():
15+
elem.tail = j
16+
else:
17+
if level and (not elem.tail or not elem.tail.strip()):
18+
elem.tail = j
19+
return elem
20+
21+
#root element
22+
root = ET.Element('bookstore', {'specialty':'novel'})
23+
24+
#book sub-element
25+
book = ET.SubElement(root, 'book', {'style':'autobiography'})
26+
27+
author = ET.SubElement(book, 'author')
28+
29+
firstName = ET.SubElement(author, 'first-name')
30+
firstName.text = 'Joe'
31+
32+
lastName = ET.SubElement(author, 'last-name')
33+
lastName.text = 'Bob'
34+
35+
award = ET.SubElement(author, 'award')
36+
award.text = 'Trenton Literary Review Honorable Mention'
37+
38+
price = ET.SubElement(book, 'price')
39+
price.text = str(12)
40+
41+
#magazine sub-element
42+
magazine = ET.SubElement(root, 'magazine', {'style':'glossy', 'frequency':'monthly'})
43+
44+
price = ET.SubElement(magazine, 'price')
45+
price.text = str(12)
46+
47+
subscription = ET.SubElement(magazine, 'subscription', {'price':'24', 'per':'year'})
48+
49+
#write to file
50+
tree = ET.ElementTree(indent(root))
51+
tree.write('bookstore2.xml', xml_declaration=True, encoding='utf-8')

0 commit comments

Comments
 (0)