码迷,mamicode.com
首页 > 编程语言 > 详细

[python 学习] 使用 xml.etree.ElementTree 模块处理 XML

时间:2017-09-15 01:48:06      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:技术   恢复   int   手册   dir   ext   一个   导入   tps   

---恢复内容开始---

导入数据(读文件和读字符串)

本地文件 country_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

import xml.etree.ElementTree as ET
tree = ET.parse(country_data.xml)
root = tree.getroot()

从字符串中读取 xml

root = ET.fromstring(country_data_as_string)

Element.tag 、Element.text 和 Element.attributes

# root.tag 读取 tag 名
# root.attrib 读取 attributes
# root[0][1].rank 读取文本值
print root.tag         #输出根节点元素<data>的tag名:data
print root.attrib      #输出根节点元素<data>的attributes(空值):{}
print root[0][2].text  #输出第一个<country>的子元素<gdppc>的文本值:141100

技术分享

Element.iter()

# root.iter(‘neighbor‘)查找所有子孙元素
for neighbor in root.iter(neighbor):
    print neighbor.attrib

技术分享

find() 和 findall()

# find()返回第一个子元素
print root.find(country)
# fund() 返回所有子元素
print root.findall(country)

技术分享

照搬手册:

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

[python 学习] 使用 xml.etree.ElementTree 模块处理 XML

标签:技术   恢复   int   手册   dir   ext   一个   导入   tps   

原文地址:http://www.cnblogs.com/natian-ws/p/7523589.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!