File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ ## 1.构建xml文件
2+ ``` python
3+ # -*- coding: utf-8 -*-
4+ import xml.etree.ElementTree as ET
5+
6+ root = ET .Element(" html" )
7+ head = ET .SubElement(root, " head" )
8+ title = ET .SubElement(head, " title" )
9+ title.text = " Title"
10+
11+ body = ET .SubElement(root, " body" )
12+ body.set(" bgcolor" , " #ffffff" )
13+ body.text = " Hello, World!"
14+
15+ tree = ET .ElementTree(root)
16+ tree.write(" hello.xhtml" )
17+ ```
18+
19+ hello.xhtml:
20+
21+ <html><head><title>Title</title></head><body bgcolor="#ffffff">Hello, World!</body></html>
22+
23+ ## 2.加载xml文件
24+ ``` python
25+ # -*- coding: utf-8 -*-
26+ import xml.etree.ElementTree as ET
27+
28+ tree = ET .parse(" hello.xhtml" )
29+ print tree.findtext(" head/title" )
30+ root = tree.getroot()
31+ # do something here
32+ tree.write(" out.xml" )
33+ ```
34+
35+ 输出:
36+
37+ Title
38+
39+ out.xml:
40+
41+ <html><head><title>Title</title></head><body bgcolor="#ffffff">Hello, World!</body></html>
You can’t perform that action at this time.
0 commit comments