python xml
来源:互联网 发布:java关闭mongodb连接 编辑:程序博客网 时间:2024/06/10 19:42
xml源
<?xml version="1.0"?><data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank updated="yes">69</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country></data>
遍历
import xml.etree.ElementTree as ETtree = ET.parse('example.xml')root = tree.getroot()print(root.tag)# data#遍历xml文档for child in root: print(child.tag, child.attrib) # 输出为 # country {'name': 'Liechtenstein'} # country {'name': 'Singapore'} # country {'name': 'Panama'} for i in child: print(i.tag,i.text) # rank 69 # year 2011 # gdppc 13600 # neighbor None # neighbor None# 只遍历year 节点for node in root.iter('year'): print(node.tag, node.text) # year 2008 # year 2011 # year 2011
更新与删除
import xml.etree.ElementTree as ETtree = ET.parse('example.xml')root = tree.getroot()for node in root.iter('year'): new_year = int(node.text) + 1 node.text = str(new_year) # 更新属性 node.set('updated','yes')tree.write("example_new2.xml")# 删除nodefor country in root.findall('country'): rank = int(country.find('rank').text) if rank > 50: root.remove(country)tree.write('example_new3.xml')
生成打印xml
import xml.etree.ElementTree as ETnew_xml = ET.Element("namelist")name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})age = ET.SubElement(name, "age", attrib={"checked": "no"})sex = ET.SubElement(name, "sex")sex.text = '33'name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})age = ET.SubElement(name2, "age")age.text = '19'et = ET.ElementTree(new_xml) # 生成文档对象et.write("test.xml", encoding="utf-8", xml_declaration=True)ET.dump(new_xml) # 打印生成的格式
0 0
- Python & XML
- Python & XML
- python xml
- python xml
- Python XML
- python xml
- python xml
- xml python
- python xml
- Python---xml
- python xml
- python xml
- python 解析XML xml.dom
- python 解析XML xml.dom
- python 解析XML xml.dom
- python解析xml(创建xml)
- python 解析XML xml.dom
- python 解析XML xml.dom
- hihocoder 1158 二分图
- FameView脚本对变量的赋值
- 博客
- 光流法
- C语言 strlen函数实现
- python xml
- 一次面试官的经历
- hdu 2013 蟠桃记
- fcntl函数详解
- 变量直接的运算
- Ubuntu上用caffe的SSD方法训练umdfaces数据集
- Maven插件--多代码目录插件
- 什么是VLAN
- Redis常用命令-String