|
@@ -0,0 +1,46 @@
|
|
|
+# -*-coding:utf-8-*-
|
|
|
+#支持中文必须加上上面一句话
|
|
|
+
|
|
|
+__author__ = 'Administrator'
|
|
|
+
|
|
|
+import xml.dom.minidom
|
|
|
+
|
|
|
+
|
|
|
+class UsestudioXML:
|
|
|
+ #在内存中创建一个空的文档
|
|
|
+ doc = xml.dom.minidom.Document()
|
|
|
+ #数据
|
|
|
+ managerList =[{'name': 'joy', 'age': 27, 'sex': '女'},
|
|
|
+ {'name': 'tom', 'age': 30, 'sex': '男'},
|
|
|
+ {'name': 'ruby', 'age': 29, 'sex': '女'}
|
|
|
+ ]
|
|
|
+ def createRoot(self):
|
|
|
+ #创建一个根节点Managers对象
|
|
|
+ root = self.doc.createElement('Managers')
|
|
|
+ #设置根节点的属性
|
|
|
+ root.setAttribute('company', 'xx科技')
|
|
|
+ root.setAttribute('address', '科技软件园')
|
|
|
+ #将根节点添加到文档对象中
|
|
|
+ self.doc.appendChild(root)
|
|
|
+ def addNode(self):
|
|
|
+ for i in self.managerList:
|
|
|
+ nodeManager = self.doc.createElement('Manager')
|
|
|
+ nodeName = self.doc.createElement('name')
|
|
|
+ #给叶子节点name设置一个文本节点,用于显示文本内容
|
|
|
+ nodeName.appendChild(self.doc.createTextNode(str(i['name'])))
|
|
|
+
|
|
|
+ nodeAge = self.doc.createElement("age")
|
|
|
+ nodeAge.appendChild(self.doc.createTextNode(str(i["age"])))
|
|
|
+
|
|
|
+ nodeSex = self.doc.createElement("sex")
|
|
|
+ nodeSex.appendChild(self.doc.createTextNode(str(i["sex"])))
|
|
|
+
|
|
|
+ #将各叶子节点添加到父节点Manager中,
|
|
|
+ #最后将Manager添加到根节点Managers中
|
|
|
+ nodeManager.appendChild(nodeName)
|
|
|
+ nodeManager.appendChild(nodeAge)
|
|
|
+ nodeManager.appendChild(nodeSex)
|
|
|
+ root.appendChild(nodeManager)
|
|
|
+ #开始写xml文档
|
|
|
+ fp = open('c:\\wcx\\Manager.xml', 'w')
|
|
|
+ self.doc.writexml(fp, indent='\t', addindent='\t', newl='\n', encoding="utf-8")
|