Chinaunix
标题:
一个使用ElementTree的xml添加元素,删除,更新,读取的类
[打印本页]
作者:
yangward
时间:
2010-03-23 20:59
标题:
一个使用ElementTree的xml添加元素,删除,更新,读取的类
在搜索引擎找到很多python操作xml的文章,但都不完整,我这里这个整理了一个,希望大家给点意见
problem.xml
<?xml version='1.0' encoding='UTF-8'?>
<book>
<date>2010.3.10</date>
<version>Three</version>
<dbcm_version>good</dbcm_version></book>
复制代码
dbcm_xml.py
#!/usr/bin/env python
#coding=UTF-8
#用于某个xml的属性值
import os,sys,xml.etree.ElementTree as ET
class DbcmXml:
def __init__(self,filePath):
self.filePath = filePath
print '文件路径 %s' %filePath
print ET.parse(filePath)
self.xmlFile = os.path.abspath(__file__)
self.xmlFile = os.path.dirname(self.xmlFile)
self.xmlFile = os.path.join(self.xmlFile,self.filePath)
try:
self.dom = ET.parse(filePath)
self.root = self.dom.getroot()
except Exception,inst:
print "打开%s 文件时候遇到错误" %self.filePath
##输出某个属性的text内容
def getElementText(self,elementName):
self.elementName = elementName
if self.root.find(self.elementName) ==None:
print ' %s None' %self.elementName
## 更新某个已经存在的元素的text内容
def updateElementText(self,elementName,textValue):
for self.item in self.root:
self.oldElement = self.root.find(elementName)
self.root.remove(self.oldElement)
self.newElement = ET.SubElement(self.root,elementName)
self.newElement.text = textValue
tree = ET.ElementTree(self.root)
tree.write("problem.xml","UTF-8")
## 添加某个元素进去
def addElement(self,elementName,textValue):
if self.root.find(elementName) ==None:
child = ET.SubElement(self.root,elementName)
child.text = textValue
try:
tree = ET.ElementTree(self.root)
tree.write("problem.xml",encoding="UTF-8")
except Exception,inst:
print "写入文件出错 %s " %inst
##删除某个元素
def delElement(self,elementName,textValue):
#print self.root.find(elementName).text
for self.item in self.root:
self.oldElement == elementName
self.oldElement = self.root.find(elementName)
if self.oldElement !=None:
self.root.remove(self.oldElement)
tree = ET.ElementTree(self.root)
tree.write("problem.xml","UTF-8")
#self.newElement = ET.SubElement(self.root,elementName)
#self.newElement.text = textValue
tree = ET.ElementTree(self.root)
tree.write("problem.xml","UTF-8")
test = DbcmXml('problem.xml')
test.getElementText('dbcm_version')
test.updateElementText('dbcm_version','good')
#test.addElement('google','man')
test.delElement('google','man')
复制代码
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2