python使用xml.etree.elementtree模块

python2.7.15 xml参考文档

简易化使用:

一、打开xml文件

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')    这种方法最好配合try/except
root = tree.getroot()

或者:

推荐:
with open(xml_path, 'rt') as f:
	tree = xml.etree.ElementTree.parse(f)

二、查找节点/元素

node = tree.find(".//*[name1=‘text1’]") 多级查找某个节点,该节点有一个叫name1的子节点并且子节点的文本区的值等于text1。find参数是XPATH语法,其中//表示在当前元素往下多级查找节点,*表示查找所有的一级子节点/元素。

syntaxmeaning
//Selects all subelements, on all levels beneath the current element (search the entire subtree). For example, “.//egg” selects all “egg” elements in the entire tree.
*Selects all child elements. For example, “*/egg” selects all grandchildren named “egg”.

三、访问节点值

  • node.tag node.attrib node.text 表示访问当前元素的一些信息。
node[0].text 访问当前元素中包含的第一个子元素的text值。
  • 如果node指代root,则node[0].text 得到的值是\n\t,可用list函数查看这两个特殊的控制符号,如下xml,
    text指的就是与<country…之间的文本内容,如果想查看元素中包含的子元素中的文本内容,可用函数itertext。
node[0][1].text 访问当前元素第一个子元素中第二个元素的text值。
  • 如果node指代的当前元素是root根元素,则如下xml文件,node[0][1].text就是得到值2008:
<?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>
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值