Skip to content

Commit a9527e5

Browse files
authored
Create xml.md
1 parent 764c0bd commit a9527e5

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

‎CorePythonProgramming/xml.md‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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>

0 commit comments

Comments
 (0)