question No. 0017: Write the contents of the Student.xls file in question No. 0014 to the Student.xml file, as
is shown below:
<?xml version="1.0"encoding="UTF-8"?><root><students><!--Student Information Form"ID": [Name, Maths, Chinese, English]-{ "1": ["Zhang San", 150, 120, 100], "2": ["John Doe", 90, 99, 95], "3": ["Harry", 60, 66, 68]}</students></root>
We're going to use the XML module here, and I'm going to use Xml.etree to do it.
Code:
ImportxlrdImportXml.dom.minidom as MDdefget_xls_data (filename): book=xlrd.open_workbook (filename) sheet=book.sheet_by_index (0) content= {} forIinchRange (sheet.nrows): Content[i+1] = sheet.row_values (i) [1:] returncontentdefWrite_to_xml (xlscontent): XMLFile= Md. Document ()#Create a new XML fileRoot= Xmlfile.createelement ('Root')#Create a nodeStudents = Xmlfile.createelement ('Students')#Create a nodeXmlfile.appendchild (Root)#Add the root node to the fileRoot.appendchild (students)#Add the students node under rootComment= Xmlfile.createcomment ('Student Information Sheet "id": [Name, Math, Chinese, English]')#Create a commentStudents.appendchild (comment)#add comment Under the Students tabxmlcontent= Xmlfile.createtextnode (str (xlscontent))#Create a text nodeStudents.appendchild (xmlcontent) adds text content under the students tag with open ('Students.xml','WB') as F:f.write (Xmlfile.toprettyxml (Encoding='Utf-8'))#Write FileWrite_to_xml (Get_xls_data ('Students.xls'))
Note:
1. get_xls_data (filename) function reads content from XLS
2. XML related operations are not difficult, see post code comments
3. Note that the content obtained through Get_xls_data () is Dict, and the createTextNode () method requires that the contents pair be created as STR, with type (variable name) to view the variable type
The contents of the XML file obtained are as follows:
<?xml version="1.0"encoding="Utf-8"?><root> <students> <!--student Information sheet"ID": [Name, Maths, Chinese, English]--> {1: ['Zhang San',' Max',' -',' -'], 2: ['John Doe',' -',' About',' the'], 3: ['Harry',' -',' the',' the']} </students></root>
Line up, do not know whether it can be a branch, but the content does not affect
"Python practice" 0017-Writes the contents of the XLS file to an XML file