题目
将 第 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
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
def write_xml(xmlname, data, comment): root = etree.Element('root') comm = etree.Comment(comment) root.append(comm) child = etree.SubElement(root, xmlname) child.text = str(data)
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)
|
参考