Python XML操作

XML(可扩展性标记语言)是一种非常常用的文件类型,主要用于存储和传输数据。在编程中,对XML的操作也非常常见。

本文根据python库文档中的xml.etree.ElementTree类来进行介绍XML的解析:https://docs.python.org/3.5/library/xml.etree.elementtree.html 

BTW,xml.etree.cElementTree模块从3.3以后就被弃用了.

XML格式

首先,来看一下XML所包含的元素类型

1. 标签 <tag>

2. 属性 <tag  name="attribute">

3. 数据 <data>1<data>

 例如 xml段:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

 

XML操作

  • 读取

#从变量读取,参数为XML段,返回的是一个根Element对象
root = ET.fromstring(country_data_as_string)

#从xml文件中读取,用getroot获取根节点,根节点也是Element对象
tree = ET.parse('file.xml')
root = tree.getroot()
  • 访问

    • 访问Element对象的标签、属性和值
tag = element.tag
attrib = element.attrib
value = element.text
    • 访问子节点
#打印根节点的标签和属性,获取
for child in root:
    print(child.tag, child.attrib)
  • 查找操作

    • Element元素迭代子元素:Element.iter("tag"),可以罗列该节点所包含的所有其他节点(element对象)
#打印根节点中所有的neighbor对象的name属性
for neighbor in root.iter('neighbor'):
    print(neighbor.attrib['name'])
    • Element.findall("tag"):查找当前元素为“tag”的直接子元素
#findall只能用来查找直接子元素,不能用来查找rank,neighbor等element
for country in root.findall('country'):
    rank = country.find('rank').text
    name = country.find('rank').text
    neig = country.find('neighbor').attrib
    print(rank, name,neig)
    • Element.find("tag"):查找为tag的第一个直接子元素
#返回第一个tag为country的element,如没有,返回None
firstCountry = root.find("country")
print(firstCountry)
  • 创建xml文件

__author__ = 'xua'

import xml.etree.ElementTree as ET
#创建根节点
a = ET.Element("root")
#创建子节点,并添加属性
b = ET.SubElement(a,"sub1")
b.attrib = {"name":"name attribute"}
#创建子节点,并添加数据
c = ET.SubElement(a,"sub2")
c.text = "test"

#创建elementtree对象,写文件
tree = ET.ElementTree(a)
tree.write("test.xml")

创建的新文件内容为:<root><sub1 name="name attribute" /><sub2>test</sub2></root>

  • 修改XML文件

    • ElementTree.write("xmlfile"):更新xml文件
    • Element.append():为当前element对象添加子元素(element)
    • Element.set(key,value):为当前element的key属性设置value值
    • Element.remove(element):删除为element的节点
#读取待修改文件
updateTree = ET.parse("test.xml")
root = updateTree.getroot()
#创建新节点并添加为root的子节点
newEle = ET.Element("NewElement")
newEle.attrib = {"name":"NewElement","age":"20"}
newEle.text = "This is a new element"
root.append(newEle)

#修改sub1的name属性
sub1 = root.find("sub1")
sub1.set("name","New Name")

#修改sub2的数据值
sub2 = root.find("sub2")
sub2.text = "New Value"

#写回原文件
updateTree.write("test.xml")

更新完的文件为:<root><sub1 name="New Name" /><sub2>New Value</sub2><NewElement age="20" name="NewElement">This is a new element</NewElement></root>

 

总结

 XML的操作比较常见,当然也有很多第三方的库可以使用,所需要做的操作无非就是常用的读写xml文件、元素节点的增删改查,大家还可以在python官方文档上学习更多的操作。

https://docs.python.org/3.5/library/xml.etree.elementtree.html 

 

posted on 2016-05-15 15:59  Alvin_Xu  阅读(33904)  评论(0编辑  收藏  举报