python用elementtree处理XML文件

本文详细介绍了如何使用Python的xml.etree.ElementTree模块解析、操作和生成XML文件,包括获取元素属性、遍历元素、添加和删除元素等内容,适合Python XML处理初学者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
python用elementtree处理XML文件
2010年07月04日 18:57

---------------------------------------------------------------貌似很简单,直接试用一下就知道了。。。
from xml.etree import ElementTree

a= '''<?xml version="1.0"?>
<root item_key1='ikey1' item_key2='iKey2' attriball='all' >
    root text   
    <subEle1 subAttrib='subAttrib1' /> sub1's tails
    <subEle2 subItem1="ele21" subItem2="ele22">
        subEle2 text
        <sub2sub1>sub2'sub1 text</sub2sub1>
        <sub2sub2>sub2'sub2 text</sub2sub2>
        <sub2sub3>
            <sub231>just 4 fun</sub231>
        </sub2sub3>
        <tag1>tag1's text1</tag1>
        <tag1>tag1's text2</tag1>
        <tag1>tag1's text3</tag1>
        <tag1>tag1's text4</tag1>    
    </subEle2>
    <subEle3>subEle3's text</subEle3>
</root>'''

r = ElementTree.fromstring(a)         # 从字符串中生成xml树

>>> ElementTree.tostring(r)           # 显示
>>> ElementTree.dump(r)
>>> ElementTree.dump(r.find('subEle2'))
>>> dir(r)                                    # o是2.5版本
['__delitem__', '__delslice__', '__doc__', '__getitem__', '__getslice__', '__init__', '__len__', '__
module__', '__repr__', '__setitem__', '__setslice__', '_children', 'append', 'attrib', 'clear', 'fin
d', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'insert', 'items', 'keys', 'makeelem
ent', 'remove', 'set', 'tag', 'tail', 'text']

------------------------- root本身的属性等
>>> str.strip(r.text)        # tag、text、items、attrib的所指
'root text'
>>> r.tag
'root'
>>> r.items()         # 是个2维元组的列表
[('attriball', 'all'), ('item_key2', 'iKey2'), ('item_key1', 'ikey1')]

>>> r.attrib          # 是个集合
{'attriball': 'all', 'item_key2': 'iKey2', 'item_key1': 'ikey1'}

>>> r.get('attriball')   # 如果没有该属性返回None哈。
'all'

>>> r.keys()
['attriball', 'item_key2', 'item_key1']

>>> if r.attrib.has_key("item_key2"):
...     print r.attrib['item_key2']
...
iKey2

------------------------------------- root的孩子
>>> for ele in r.getiterator():           # 所有的元素以及内容, 2.7以后用iter()代替了。
...     print ele.tag
...     if ele.text:
...         print '-->%s' % str.strip(ele.text)
...
   
>>> r.find('subEle1').tail      # 元素的尾巴,貌似元素之间没人管的东东
" sub1's tails\n    "

>>> r.getiterator('tag1')           # 得到特定tag的元素,可以跨层,但是find不行。
[<Element tag1 at c9db70>, <Element tag1 at c9dbc0>, <Element tag1 at c9dc60>, <Element tag1 at c9dd
00>]
>>> print r.find('tag1')
None

>>> r.find('subEle2/tag1')
<Element tag1 at c9db70>
>>> r.findall('subEle2/tag1')
[<Element tag1 at c9db70>, <Element tag1 at c9dbc0>, <Element tag1 at c9dc60>, <Element tag1 at c9dd
00>]

------------------------------------------- 写元素树
n = ElementTree.ElementTree()
r = ElementTree.Element('root')
n._setroot(r)
>>> ElementTree.dump(n)
<root />

ElementTree.SubElement(r, 'subEle1', {'subAttrib' : "subAttrib1"})
t = ElementTree.Element("subEle2", {'subItem1' : 'ele21', 'subItem2' : 'ele22'})
t.text = "subEle2 text"        # 属性可以用set来修改。
r.append(t)

for i in range(1, 5):
    tt = ElementTree.Element("tag1")
    tt.text = "tag1's text%s" % i
    t.append(tt)
   
t = r.find('subEle1')
t.tail = "subele1's tail"   
   
n.write(r'c:\test.xml',"utf-8")
-------------------------------------------------
- <root>
<subEle1 subAttrib="subAttrib1" />
subele1's tail
- <subEle2 subItem1="ele21" subItem2="ele22">
subEle2 text
<tag1>tag1's text1</tag1>
<tag1>tag1's text2</tag1>
<tag1>tag1's text3</tag1>
<tag1>tag1's text4</tag1>
</subEle2>
</root>
---------------------------------------------------从文件中创建ElementTree

>>> x = ElementTree.ElementTree(file=r'c:\test.xml') # 从文件读出
>>> ElementTree.dump(x)

>>> r = x.getroot()         #得到根节点
>>> a = r.find('subEle1')   # 找到子节点
>>> ElementTree.dump(a)
<subEle1 subAttrib="subAttrib1" />subele1's tail
>>> a.set('new', 'new1')    # 设置新属性
>>> ElementTree.dump(a)
<subEle1 new="new1" subAttrib="subAttrib1" />subele1's tail
>>> r.remove(a)            # 删除一个节点。。。

>>> a = r.find('subEle2')        #   删除1级节点下面的节点。。。
>>> for i in a.findall('tag1'):
...     a.remove(i)

 

转自:http://hi.baidu.com/derris/blog/item/e0e3b850e7abbe6f84352436.html

 

附上 PYTHON 官方网址:

关于ElementTree类的成员方法:

http://docs.python.org/library/xml.etree.elementtree.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值