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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
| from lxml import etree
bookStore = etree.Element("bookstore")
book1 = etree.SubElement(bookStore, "book")
book2 = etree.SubElement(bookStore, "book", attrib={"category":"children"})
book1.attrib["category"] = "cooking"
title1 = etree.Element("title", lang="en")
title1.text = "Everyday Italian"
book1.append(title1)
etree.SubElement(book1, "author").text = "Giada De Lausadlf"
etree.SubElement(book1, "year").text = "2003"
etree.SubElement(book1, "price").text = "40.3"
title2 = etree.Element("title")
title2.set("lang", title1.get("lang"))
title2.text = "Harry Potter"
book2.append(title2)
etree.SubElement(book2, "author").text = "Giada De Lausadlf"
etree.SubElement(book2, "year").text = "2003"
etree.SubElement(book2, "price").text = "40.3"
xmlBytes = etree.tostring(bookStore, encoding="UTF-8", pretty_print=True, xml_declaration=True)
xmlstr = etree.tounicode(bookStore, pretty_print=True)
etree.dump(bookStore)
:
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Lausadlf</author>
<year>2003</year>
<price>40.3</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>Giada De Lausadlf</author>
<year>2003</year>
<price>40.3</price>
</book>
</bookstore>
xmlRoot = xmlTree.getroot()
for childNode in xmlRoot:
print(childNode.tag, childNode.attrib)
:
book {'category': 'cooking'}
book {'category': 'children'}
|