第15题:将 第 0012 题中的 student.xls 文件中的内容写到 student.xml 文件中,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<students>
<!--
学生信息表
"id" : [名字, 数学, 语文, 英文]
-->
{
"1" : ["张三", 150, 120, 100],
"2" : ["李四", 90, 99, 95],
"3" : ["王五", 60, 66, 68]
}
</students>
</root>
#!/usr/bin/env python3
# -*- coding : utf-8 -*-
from pyexcel_xls import get_data
from xml.dom.minidom import Document
import json
data = get_data('student.xls')
#with open('student.xml','w') as s:
# for i in data['student']:
# line = []
# for j in range(len(i)):
# line.append(str(i[j]))
# line.append('\t')
# line.append('\n')
# s.write(''.join(line))
doc = Document()
root_node = doc.createElement("root")
doc.appendChild(root_node)
stu_node = doc.createElement("students")
root_node.appendChild(stu_node)
stu_node.appendChild(doc.createComment(' 学生信息表\n \t"id" : [名字,数学,语文,英语] \n'))
student_xls_format = {}
for ele in data['student']:
values = []
key = ""
for i in range(len(ele)):
if i == 0:
key = str(ele[i])
else:
values.append(ele[i])
student_xls_format[key] = values
print(json.dumps(student_xls_format))
dic_node = doc.createTextNode(json.dumps(student_xls_format,ensure_ascii = False,indent = 4))
stu_node.appendChild(dic_node)
with open("student.xml",'w') as s:
s.write(doc.toprettyxml())
输出如下:
问题:每个学生之间换行,有什么简便的办法呢?