Python之xml文件处理(一)——使用ElementTree遍历xml

发现python上有关xml的实现方法还是蛮多的,第三方的框架也不少,但是其中没有像dom4j那样名声响亮的框架。所以,还是中规中居地介绍python的故有方法吧。

今天,先介绍一个ElementTree,看着还顺眼些。详细说明在代码注释中,结果在后面。

1#coding:utf-8 2''' 3Created on 20151124 5@author: neil 6''' 7from xml.etree import ElementTree 8 9#xml内容以文件形式传入 10#filepath='' 11with open(filepath,'rt') as f: 12#     tree=ElementTree.parse(f) 13 14#xml内容以字符串形式传入 15tree=ElementTree.fromstring('''<?xml version="1.0" encoding="utf-8"?> 16<catalog> 17       <maxid id='0'>4</maxid>尾巴 18       <login id='1' username="pytest" passwd='123456'> 19              <caption>Python</caption> 20             <item id="4"> 21                    <caption>测试</caption> 22            </item> 23    </login> 24    <item id="2"> 25            <caption>Zope</caption> 26            <caption>JJJ</caption> 27    </item> 28<mux>sdfsdfsdfs</mux> 29</catalog>''') 30 31for node in tree.iter():#深度搜索、树的先序遍历 32    print type(node) 33    print 'tag:',node.tag#元素标签名 34    print 'tail:',node.tail#</XXX>后面的字符串,多半是回车换行。根结点的结束标签后面文档结束,所以是None。 35    print 'attrib:',node.attrib#字典类型,字典的项对应元素属性,字典的键对应属性名称,字典的值对应属性值 36    print 'attrib-id-default:',node.attrib.get('id','NULL')#字典方法,按键取值,如果键不存在,就取默认值。默认值由第二个参数规定。 37    print 'attrib-id:',node.attrib.get('id')#字典方法,按键取值,如果键不存在,就取None,不会报错。 38    print 'attrib.items:',node.attrib.items()#二元元组的列表,列表的每一个项是一个二元元组,元组的前一个值是xml元素属性的名称,后一个值是属性的值。 39    print 'attrib.keys:',node.attrib.keys()#以列表的形式列举元素的所有属性名称 40    print 'find-caption:',node.find('caption')#只在该结点的所有子节点中选择符合元素名称的第一个子节点 41    print 'find-item:',node.find('item') 42    print 'findall:',node.findall('caption')#只在该结点的所有子节点中选择符合元素名称的所有子节点,范围类型为列表 43    print 'findtext-caption:',node.findtext('caption')#只在该结点的所有子节点中选择符合元素内容的第一个子节点 44    print 'getchildren:',node.getchildren() #所有子节点以列表形式给出 45    print 'iter:',node.iter() 46    for n in node.iter():#深度搜索、树的先序遍历该结点下的子树 47        print '++++',n.tag 48    print '- - - - - - - - - - - - - - - - '

输出结果如下:

1<class 'xml.etree.ElementTree.Element'> 2tag: catalog 3tail: None 4attrib: {} 5attrib-id-default: NULL 6attrib-id: None 7attrib.items: [] 8attrib.keys: [] 9find-caption: None 10find-item: <Element 'item' at 0x7f738e1f1c10> 11findall: [] 12findtext-caption: None 13getchildren: [<Element 'maxid' at 0x7f738e1f1850>, <Element 'login' at 0x7f738e1f1890>, <Element 'item' at 0x7f738e1f1c10>, <Element 'mux' at 0x7f738e1f1cd0>] 14iter: <generator object iter at 0x7f738e1e72d0> 15++++ catalog 16++++ maxid 17++++ login 18++++ caption 19++++ item 20++++ caption 21++++ item 22++++ caption 23++++ caption 24++++ mux 25- - - - - - - - - - - - - - - -  26<class 'xml.etree.ElementTree.Element'> 27tag: maxid 28tail: 尾巴 29        30attrib: {'id': '0'} 31attrib-id-default: 0 32attrib-id: 0 33attrib.items: [('id', '0')] 34attrib.keys: ['id'] 35find-caption: None 36find-item: None 37findall: [] 38findtext-caption: None 39getchildren: [] 40iter: <generator object iter at 0x7f738e1e7370> 41++++ maxid 42- - - - - - - - - - - - - - - -  43<class 'xml.etree.ElementTree.Element'> 44tag: login 45tail:  46     47attrib: {'username': 'pytest', 'passwd': '123456', 'id': '1'} 48attrib-id-default: 1 49attrib-id: 1 50attrib.items: [('username', 'pytest'), ('passwd', '123456'), ('id', '1')] 51attrib.keys: ['username', 'passwd', 'id'] 52find-caption: <Element 'caption' at 0x7f738e1f1950> 53find-item: <Element 'item' at 0x7f738e1f1a10> 54findall: [<Element 'caption' at 0x7f738e1f1950>] 55findtext-caption: Python 56getchildren: [<Element 'caption' at 0x7f738e1f1950>, <Element 'item' at 0x7f738e1f1a10>] 57iter: <generator object iter at 0x7f738e1e7370> 58++++ login 59++++ caption 60++++ item 61++++ caption 62- - - - - - - - - - - - - - - -  63<class 'xml.etree.ElementTree.Element'> 64tag: caption 65tail:  66              67attrib: {} 68attrib-id-default: NULL 69attrib-id: None 70attrib.items: [] 71attrib.keys: [] 72find-caption: None 73find-item: None 74findall: [] 75findtext-caption: None 76getchildren: [] 77iter: <generator object iter at 0x7f738e1e73c0> 78++++ caption 79- - - - - - - - - - - - - - - -  80<class 'xml.etree.ElementTree.Element'> 81tag: item 82tail:  83     84attrib: {'id': '4'} 85attrib-id-default: 4 86attrib-id: 4 87attrib.items: [('id', '4')] 88attrib.keys: ['id'] 89find-caption: <Element 'caption' at 0x7f738e1f1bd0> 90find-item: None 91findall: [<Element 'caption' at 0x7f738e1f1bd0>] 92findtext-caption: 测试 93getchildren: [<Element 'caption' at 0x7f738e1f1bd0>] 94iter: <generator object iter at 0x7f738e1e73c0> 95++++ item 96++++ caption 97- - - - - - - - - - - - - - - -  98<class 'xml.etree.ElementTree.Element'> 99tag: caption 100tail:  101             102attrib: {} 103attrib-id-default: NULL 104attrib-id: None 105attrib.items: [] 106attrib.keys: [] 107find-caption: None 108find-item: None 109findall: [] 110findtext-caption: None 111getchildren: [] 112iter: <generator object iter at 0x7f738e1e7410> 113++++ caption 114- - - - - - - - - - - - - - - -  115<class 'xml.etree.ElementTree.Element'> 116tag: item 117tail:  118 119attrib: {'id': '2'} 120attrib-id-default: 2 121attrib-id: 2 122attrib.items: [('id', '2')] 123attrib.keys: ['id'] 124find-caption: <Element 'caption' at 0x7f738e1f1c50> 125find-item: None 126findall: [<Element 'caption' at 0x7f738e1f1c50>, <Element 'caption' at 0x7f738e1f1c90>] 127findtext-caption: Zope 128getchildren: [<Element 'caption' at 0x7f738e1f1c50>, <Element 'caption' at 0x7f738e1f1c90>] 129iter: <generator object iter at 0x7f738e1e7370> 130++++ item 131++++ caption 132++++ caption 133- - - - - - - - - - - - - - - -  134<class 'xml.etree.ElementTree.Element'> 135tag: caption 136tail:  137             138attrib: {} 139attrib-id-default: NULL 140attrib-id: None 141attrib.items: [] 142attrib.keys: [] 143find-caption: None 144find-item: None 145findall: [] 146findtext-caption: None 147getchildren: [] 148iter: <generator object iter at 0x7f738e1e73c0> 149++++ caption 150- - - - - - - - - - - - - - - -  151<class 'xml.etree.ElementTree.Element'> 152tag: caption 153tail:  154     155attrib: {} 156attrib-id-default: NULL 157attrib-id: None 158attrib.items: [] 159attrib.keys: [] 160find-caption: None 161find-item: None 162findall: [] 163findtext-caption: None 164getchildren: [] 165iter: <generator object iter at 0x7f738e1e73c0> 166++++ caption 167- - - - - - - - - - - - - - - -  168<class 'xml.etree.ElementTree.Element'> 169tag: mux 170tail:  171 172attrib: {} 173attrib-id-default: NULL 174attrib-id: None 175attrib.items: [] 176attrib.keys: [] 177find-caption: None 178find-item: None 179findall: [] 180findtext-caption: None 181getchildren: [] 182iter: <generator object iter at 0x7f738e1e7370> 183++++ mux 184- - - - - - - - - - - - - - - -

Element具有的属性和方法:

  • tag

  • A string identifying what kind of data this element represents (the element type, in other words).

  • text

  • The text attribute can be used to hold additional data associated with the element. As the name implies this attribute is usually a string but may be any application-specific object. If the element is created from an XML file the attribute will contain any text found between the element tags.

  • tail

  • The tail attribute can be used to hold additional data associated with the element. This attribute is usually a string but may be any application-specific object. If the element is created from an XML file the attribute will contain any text found after the element’s end tag and before the next tag.

  • attrib

  • A dictionary containing the element’s attributes. Note that while the attrib value is always a real mutable Python dictionary, an ElementTree implementation may choose to use another internal representation, and create the dictionary only if someone asks for it. To take advantage of such implementations, use the dictionary methods below whenever possible.

The following dictionary-like methods work on the element attributes.

  • clear()

  • Resets an element. This function removes all subelements, clears all attributes, and sets the text and tail attributes to None.

  • get(key,default=None)

  • Gets the element attribute named key.

    Returns the attribute value, or default if the attribute was not found.

  • items()

  • Returns the element attributes as a sequence of (name, value) pairs. The attributes are returned in an arbitrary order.

  • keys()

  • Returns the elements attribute names as a list. The names are returned in an arbitrary order.

  • set(key,value)

  • Set the attribute key on the element to value.

The following methods work on the element’s children (subelements).

  • append(subelement)

  • Adds the element subelement to the end of this elements internal list of subelements.

  • extend(subelements)

  • Appends subelements from a sequence object with zero or more elements. RaisesAssertionError if a subelement is not a valid object.

    New in version 2.7.

  • find(match)

  • Finds the first subelement matching matchmatch may be a tag name or path. Returns an element instance orNone.

  • findall(match)

  • Finds all matching subelements, by tag name or path. Returns a list containing all matching elements in document order.

  • findtext(match,default=None)

  • Finds text for the first subelement matching matchmatch may be a tag name or path. Returns the text content of the first matching element, or_default_ if no element was found. Note that if the matching element has no text content an empty string is returned.

  • getchildren()

  • Deprecated since version 2.7:Uselist(elem) or iteration.

  • getiterator(tag=None)

  • Deprecated since version 2.7:Use method Element.iter() instead.

  • insert(index,element)

  • Inserts a subelement at the given position in this element.

  • iter(tag=None)

  • Creates a tree iterator with the current element as the root. The iterator iterates over this element and all elements below it, in document (depth first) order. If tag is not None or '*', only elements whose tag equals tag are returned from the iterator. If the tree structure is modified during iteration, the result is undefined.

  • iterfind(match)

  • Finds all matching subelements, by tag name or path. Returns an iterable yielding all matching elements in document order.

    New in version 2.7.

  • itertext()

  • Creates a text iterator. The iterator loops over this element and all subelements, in document order, and returns all inner text.

    New in version 2.7.

  • makeelement(tag,attrib)

  • Creates a new element object of the same type as this element. Do not call this method, use the SubElement() factory function instead.

  • remove(subelement)

  • Removes subelement from the element. Unlike the find* methods this method compares elements based on the instance identity, not on tag value or contents.

ElementTree具有的属性和方法:

  • _setroot(element)

  • Replaces the root element for this tree. This discards the current contents of the tree, and replaces it with the given element. Use with care.element is an element instance.

  • find(match)

  • Finds the first toplevel element matching matchmatch may be a tag name or path. Same as getroot().find(match). Returns the first matching element, orNone if no element was found.

  • findall(match)

  • Finds all matching subelements, by tag name or path. Same as getroot().findall(match).match may be a tag name or path. Returns a list containing all matching elements, in document order.

  • findtext(match,default=None)

  • Finds the element text for the first toplevel element with given tag. Same as getroot().findtext(match).match may be a tag name or path.default is the value to return if the element was not found. Returns the text content of the first matching element, or the default value no element was found. Note that if the element is found, but has no text content, this method returns an empty string.

  • getiterator(tag=None)

  • Deprecated since version 2.7:Use method ElementTree.iter() instead.

  • getroot()

  • Returns the root element for this tree.

  • iter(tag=None)

  • Creates and returns a tree iterator for the root element. The iterator loops over all elements in this tree, in section order.tag is the tag to look for (default is to return all elements)

  • iterfind(match)

  • Finds all matching subelements, by tag name or path. Same as getroot().iterfind(match). Returns an iterable yielding all matching elements in document order.

    New in version 2.7.

  • parse(source,parser=None)

  • Loads an external XML section into this element tree. source is a file name or file object.parser is an optional parser instance. If not given, the standard XMLParser parser is used. Returns the section root element.

  • write(file,encoding="us-ascii",xml_declaration=None,method="xml")

  • Writes the element tree to a file, as XML. file is a file name, or a file object opened for writing.encoding[1] is the output encoding (default is US-ASCII).xml_declaration controls if an XML declaration should be added to the file. Use False for never, True for always, None for only if not US-ASCII or UTF-8 (default is None).method is either"xml","html" or"text" (default is"xml"). Returns an encoded string.

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

Python之xml文件处理(一)——使用ElementTree遍历xml - HelloWorld