您的位置:首页 > 编程语言 > Python开发

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]
'''
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: