Python处理XML
通过
import os
import sys
import fcntl
import xml.etree.ElementTree as ET
global example_xml
example_xml = '/home/example/example.xml
# 读取xml
lockf = None
if os.path.exists(example_xml):
lockf = open(example_xml)
fcntl.flock(lockf, fcntl.LOCK_EX)
tree = ET.parse(example_xml)
root = tree.getroot()
logging.info("%s open and root" % example_xml)
else:
logging.error("%s not found!" % example_xml)
sys.exit(-1)
# 解析 name 和 memory
try:
example_name = root.find("name").text
logging.info("example_name is %s" % example_name)
example['name'] = example_name
...
except:
logging.exception("Can't get example_name!")
sys.exit(-2)
# 修改添加子对象(3级) <app><color><red id='0'></red></color></app>
target = tree.find('app/color/red')
if target is None:
print "No app/color/red tag in example.xml"
sys.exit(-1)
target.attrib['id'] = '0'
# 完整添加子节点
e_size = "<size><high redid=\"0\" mode=\"square\" sizeset=\"%d\" /></size>" % size_set
new = ET.fromstring(e_size)
target = root.find(new.tag)
if target is not None:
print "Tag <%s> exists in example.xml" % new.tag
sys.exit(-3)
root.append(new)将 XML 解析为树的形式
找到元素
建立 XML 文档
使用 iterparse 来处理 XML 流
参考
Last updated