0%

Python练习册:0018

题目

    将 第 0014 题中的 student.xls 文件中的内容写到 student.xml 文件中,如下所示:
    <?xmlversion="1.0" encoding="UTF-8"?>
    <root>
    <cities>
    <!-- 
        城市信息
    -->
    {
        "1" : "上海",
        "2" : "北京",
        "3" : "成都"
    }
    </cities>
    </root>

分析

0017题一样,这次我们用lxml去操作xml对象,它比自带的xml具有更好的扩展性,还支持美化输出。

pip install lxml xlrd

代码

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
import xlrd
from lxml import etree

#读取xls
def read_xls(xlsname, sheetname):
xls = xlrd.open_workbook(xlsname)
sheet = xls.sheet_by_name(sheetname)
data = {}
for n in range(sheet.nrows):
row_d = sheet.row_values(n)
data[row_d[0]] = row_d[1]

return data


#写入到xml
def write_xml(xmlname, data, comment):
#建立root根节点
root = etree.Element('root')

#添加注释
comm = etree.Comment(comment)
root.append(comm)

#添加一个子节点city
child = etree.SubElement(root, xmlname)
#添加文字
child.text = str(data)

#生成xml树对象
tree = etree.ElementTree(root)

#写入到表格
tree.write(
xmlname + '.xml',
pretty_print=True,
xml_declaration=True,
encoding='utf-8')


if __name__ == "__main__":
comment = '城市信息'
data = read_xls('city.xls', 'city')
write_xml('city', data, comment)

参考

欢迎关注我的其它发布渠道