在Python中,ElementTree是我们常用的一个解析XML的模块

1.导入ElementTree模块

from xml.etree import ElementTree as ET

2.初始化一个ElementTree类。初始化ElementTree类常用两种方式:一种通过xml文件,一种通过字符串。

#通过xml文件初始化,test.xml是根文件夹的一个xml文件

myET=ET.parse("test.xml")#通过字符串初始化

xml="张三21"myET=ET.XML(xml)

3.查找对象

getchildren()方法会返回根节点包含的所有子节点,返回类型为ElementTree列表

find(match)方法可以根据节点名称来寻找节点内容

printmyET.getchildren()[0].textprint myET.find("name").text

两行代码输出的结果都是 张三

4.添加子节点

通过append方法添加子节点

sexET=ET.XML("男")

myET.append(sexET)

5.删除子节点

通过remove方法删除子节点

ageET=myET.find("age")

myET.remove(ageET)

6.修改内容

#修改内容

myET.find("name").text="李四"

#修改标签

myET.find("name").tag="person"

7.转换成字符串

tostring()方法可以将ElementTree对象转换成字符串

第一个参数是ElementTree对象,第二个参数是编码方式,可以缺省

ET.tostring(myET,"utf-8")

ElementTree其他方法或属性:

tagA string identifying what kind of data this element represents (the element type, in other words).textThe 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.tailThe 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.attribA 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 match. match 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 match. match may be a tag name or path. Returns the text content of the first matching element, ordefault 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 methodElement.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 theSubElement() 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.

python elementtree乱码_Python中使用ElementTree解析xml相关推荐

  1. python xlrd模块_Python中xlrd模块解析

    xlrd 导入模块 import xlrd 2.打开指定的excel文件,返回一个data对象 data = xlrd.open_workbook(file) #打开excel表,返回data对象 3 ...

  2. java解析xml实例_在java中使用dom解析xml的示例分析

    本篇文章介绍了,在java中使用dom解析xml的示例分析.需要的朋友参考下 dom是个功能强大的解析工具,适用于小文档 为什么这么说呢?因为它会把整篇xml文档装载进内存中,形成一颗文档对象树 总之 ...

  3. JAVA中利用DOM解析XML文档

    JAVA中利用DOM解析XML文档 package org.sws.utils; import java.io.File;import java.io.IOException; import java ...

  4. python模块讲解_python中常用模块详解一

    1.time 模块 import time s = time.localtime() # 把时间转化成格式化的时间,通过. 取得里面的年月日等 struct_time 格式 time.struct_t ...

  5. python解析xml文件最好选用的模块_python高级编程 之解析XML文件模块

    XML是啥?可扩展标记语言(extensible  makeup language),以.xml为后缀的文件. XML文件最大的作用在于存储和传输数据.很多Python的项目就是把产品相关配置参数存储 ...

  6. python版本回退_Python爬虫之BeautifulSoup解析之路

    上一篇分享了正则表达式的使用,相信大家对正则也已经有了一定的了解.它可以针对任意字符串做任何的匹配并提取所需信息. 但是我们爬虫基本上解析的都是html或者xml结构的内容,而非任意字符串.正则表达式 ...

  7. python getopt使用_Python命令行参数解析模块getopt使用实例

    这篇文章主要介绍了Python命令行参数解析模块getopt使用实例,本文讲解了使用语法格式.短选项参数实例.长选项参数实例等内容,需要的朋友可以参考下 格式 getopt(args, options ...

  8. python legend位置_matplotlib中legend位置调整解析

    在画一些曲线图(linecharts)时,常常会出现多条曲线同时画在一张图上面,这时候就需要对不同的曲线进行不同的标注,以使读者能够清晰地知道每条曲线代表的含义.当你画很少的几条曲线时,这时画图命令中 ...

  9. python map用法_Python中ChainMap的一种实用用法

    Python部落(python.freelycode.com)组织翻译,禁止转载,欢迎转发. 简而言之ChainMap:将多个字典视为一个,解锁Python超能力. Python标准库中的集合模块包含 ...

最新文章

  1. 华为某研究生程序员哀叹:年薪五十多万,存款一百万,却不知道未来怎么走!...
  2. [转]volley-retrofit-okhttp之我们该如何选择网路框架
  3. 关于JS数组API的总结
  4. 拓展欧几里得模板/求逆元模板(java)
  5. 关于async与await的FAQ 转
  6. 鸿蒙系统和汽车,华为鸿蒙系统和新日电动车,到底是什么关系?
  7. 洛克人红色思考型机器人叫什么_如何让机器人“好好说话”?
  8. (三)slatstack配置管理
  9. (已解决)Ubuntu下安装微软常用英文字体:Arial, Times New Roman, Calibri, Cambria等
  10. 宏碁电脑安装linux,ubuntu安装篇——acer 4750G ubuntu安装详解
  11. 核心网CN | IMSI、TMSI、P-TMSI、GUTI、S-TMSI、MSISDN、MSRN、IMEI等这些移动用户标识的辨析
  12. 1450F The Struggling Contestant(贪心+思维)
  13. PHP 测试页index.php phpinfo 空白问题
  14. 【进阶篇】前端学习路线
  15. 通过JS代码简单实现九九乘法表
  16. thinkphp6 通过命令行快速生成多应用模块报 【Command “build“ is not defined.】错误的解决办法
  17. 组网技术期末预习/复习总结
  18. 打印机出现黄色感叹号!无法查看属性和设置,开机查看打印机,打印自动变灰色问题无法使用!
  19. docx行间距怎么设置_word怎么调整行间距的两种方法
  20. 社会经济效益参考模板

热门文章

  1. 关了资源管理器电脑白屏解决办法
  2. Images Aesthetic Predictors Based on Weighted CNNs 论文翻译解读
  3. 会议通知html页面,【会议通知H5】送你最新会议邀请函H5教程,请点击查收!
  4. linux麒麟安装教程,优麒麟Ubuntu Kylin 18.04安装教程
  5. html假蓝屏死机源码,100秒内蓝屏死机的脚本源代码
  6. UltraISO 9.7.6.3829下载及安装步骤
  7. 前端基础 CSS 第十一章 使用CSS样式表 特效属性部分 ----暑假学习第九天
  8. Raphael.js 在vue中使用说明, 以杭州市地图为例
  9. Raphael绘制流程图箭头的方法
  10. Window用dos命令解压缩文件