Python文件之----XML
2015-06-02 08:06
507 查看
#coding=utf-8 from xml.dom import minidom from xml.dom.minidom import Document import xml def writeXML(filaName="test.xml"): doc = Document() feature=doc.createElement("feature") doc.appendChild(feature) father=doc.createElement("father") father.setAttribute('name','noun') #元素属性 text = doc.createTextNode('系统')#元素值 feature.appendChild(father) father.appendChild(text) son=doc.createElement("son") text = doc.createTextNode('系统')#元素值 son.appendChild(text) father.appendChild(son) f = open(filaName,'w') f.write(doc.toprettyxml(indent = '')) f.close() def readXML(fileName="test.xml"): dom = xml.dom.minidom.parse(fileName) #打开xml文档 root = dom.documentElement #得到文档元素对象 bb = root.getElementsByTagName('father') b=bb[0] print b.nodeName print b.nodeValue print b.nodeType print b.getAttribute("name") print b.firstChild.data.encode("utf-8") def main(): writeXML() # readXML() if __name__=="__main__": main()
写入的xml文档内容:
<?xml version="1.0" ?> <feature> <father name="noun"> 系统 <son>系统</son> </father> </feature>
可能写入的xml文档格式不是很好看,显示父子关系不好,可通过文本写入的方式,调整xml的格式。
对于xml的每个节点有三种属性:
nodeName为结点名字。
nodeValue是结点的值,只对文本结点有效。
nodeType是结点的类型。catalog是ELEMENT_NODE类型
第一个系统是father的标签之间的数据。
#coding=utf-8 from xml.dom import minidom from xml.dom.minidom import Document import xml def writeXML(filaName="test.xml"): doc = Document() feature=doc.createElement("feature") doc.appendChild(feature) father=doc.createElement("father") father.setAttribute('name','noun') #元素属性 text = doc.createTextNode('系统')#元素值 feature.appendChild(father) father.appendChild(text) son=doc.createElement("son") text = doc.createTextNode('系统')#元素值 son.appendChild(text) father.appendChild(son) f = open(filaName,'w') f.write(doc.toprettyxml(indent = '')) f.close() def readXML(fileName="test.xml"): dom = xml.dom.minidom.parse(fileName) #打开xml文档 root = dom.documentElement #得到文档元素对象 bb = root.getElementsByTagName('father') b=bb[0] print b.nodeName print b.nodeValue print b.nodeType print b.getAttribute("name") print b.firstChild.data.encode("utf-8") def main(): # writeXML() readXML() if __name__=="__main__": main() ''' 输出: father None 1 noun 系统 [Finished in 0.1s] '''
相关文章推荐
- 从底层理解Python的执行
- Kivy UrlRequest 与 Python unicode 以及 json
- Python Show-Me-the-Code 第 0021题 密码加密
- Python中for循环控制语句用法实例
- python实现的文件同步服务器实例
- Python中字典创建、遍历、添加等实用操作技巧合集
- Python中pip安装非PyPI官网第三方库的方法
- Python中的自省(反射)详解
- python基于xmlrpc实现二进制文件传输的方法
- python使用xmlrpclib模块实现对百度google的ping功能
- 使用pdb模块调试Python程序实例
- Python多进程并发(multiprocessing)用法实例详解
- python执行子进程实现进程间通信的方法
- 自己使用总结Python程序代码片段
- Python文档生成工具pydoc使用介绍
- Python中使用ElementTree解析XML示例
- python实现的守护进程(Daemon)用法实例
- Python2.x中文乱码问题解决方法
- python统计cpu利用率的方法
- Python脚本文件打包成可执行文件的方法