用户工具

站点工具


linux:python:xml.etree.elementtree使用

这是本文档旧的修订版!


====== xml.etree.ElementTree使用 ======

1. 创建xml root

有3种方法:

<code python> import xml.etree.ElementTree as ET

方法1

tree = ET.ElementTree(element=None, file=‘country_data.xml’) root = tree.getroot()

方法2

tree = ET.parse(‘country_data.xml’) root = tree.getroot()

方法3, 使用此方式,从内存中获取xml文件内容。比如可以先把所有的xml文件压缩,在程序中解压缩到内存,然后直接从内存中读取xml文件,这样处理的好处是减少文件数量和整体大小,以及可选的密码或加解密支持。

fh = open(‘country_data.xml’, ‘r’) # 此处使用’r’ 和‘rb’, ET都可以支持 fbuf = fh.read() root = ET.fromstring(fbuf)

</code>

2. 获取attrib

<code python> name = root.attrib[‘name’] </code>

linux/python/xml.etree.elementtree使用.1600331531.txt.gz · 最后更改: (外部编辑)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki