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+ <?xml version =' 1.0' encoding =' utf8' ?>
2+ <root ><citys >{
3+ "1": "上海",
4+ "2": "北京",
5+ "3": "成都"
6+ }</citys ></root >
Original file line number Diff line number Diff line change 1+ # -*- coding: utf-8 -*-
2+ # 第 0018 题: 将 第 0015 题中的 city.xls 文件中的内容写到 city.xml 文件中
3+ import xlrd
4+ from collections import OrderedDict
5+ import json
6+
7+ import xml .etree .cElementTree as ET
8+
9+ wb = xlrd .open_workbook ('city.xls' )
10+ sheet = wb .sheet_by_index (0 )
11+ number_of_row = sheet .nrows
12+ number_of_col = sheet .ncols
13+
14+ city = OrderedDict ()
15+
16+ for row in range (number_of_row ):
17+ city [sheet .cell (row , 0 ).value ] = sheet .cell (row , 1 ).value
18+
19+ print (city )
20+ json_str = json .dumps (city , ensure_ascii = False , indent = 4 )
21+ print (json_str )
22+
23+ root = ET .Element ('root' )
24+ cities = ET .SubElement (root , 'citys' )
25+
26+ cities .text = json_str
27+
28+ tree = ET .ElementTree (root )
29+ tree .write ('city.xml' , encoding = 'utf8' , xml_declaration = True )
You can’t perform that action at this time.
0 commit comments