1 from xml.dom.minidom importDocument2 #将self.orderDict中的信息写入本地xml文件,参数filename是xml文件名
3 defwriteInfoToXml(self, filename):4 #创建dom文档
5 doc =Document()6
7 #创建根节点
8 orderlist = doc.createElement('orderlist')9 #根节点插入dom树
10 doc.appendChild(orderlist)11
12 #依次将orderDict中的每一组元素提取出来,创建对应节点并插入dom树
13 for (k, v) inself.orderDict.iteritems():14 #分离出姓名,电话,地址,点餐次数
15 (name, tel, addr, cnt) = (v[0], k, v[1], v[2])16
17 #每一组信息先创建节点,然后插入到父节点下
18 order = doc.createElement('order')19 orderlist.appendChild(order)20
21 #将姓名插入中
22 #创建节点
23 customer = doc.createElement('customer')24 #创建下的文本节点
25 customer_text =doc.createTextNode(name)26 #将文本节点插入到下
27 customer.appendChild(customer_text)28 #将插入到父节点下
29 order.appendChild(customer)30
31 #将电话插入中,处理同上
32 phone = doc.createElement('phone')33 phone_text =doc.createTextNode(tel)34 phone.appendChild(phone_text)35 order.appendChild(phone)36
37 #将地址插入中,处理同上
38 address = doc.createElement('address')39 address_text =doc.createTextNode(addr)40 address.appendChild(address_text)41 order.appendChild(address)42
43 #将点餐次数插入中,处理同上
44 count = doc.createElement('count')45 count_text =doc.createTextNode(str(cnt))46 count.appendChild(count_text)47 order.appendChild(count)48
49 #将dom对象写入本地xml文件
50 with open(filename, 'w') as f:51 f.write(doc.toprettyxml(indent='\t', encoding='utf-8'))52
53 return