xml parser - etree

 


1. xml的构成 

 2. xml中的实体引用

 3. python etree 

  

 

4. python etree实例 

import xml.etree.ElementTree as ET


# https://docs.python.org/3/library/xml.etree.elementtree.html
# https://zhuanlan.zhihu.com/p/502584681


def main():
    tree = ET.parse('./country_data.xml')

    # 获取根元素
    root = tree.getroot()
    print("{} {}".format(type(root), root))

    # 获取指定元素
    print("root[0][1]: tag={},text={}".format(root[0][1].tag, root[0][1].text))

    # 遍历root元素下的所有一级子元素
    for child in root:
        print("---tag:{}, attr:{}, txt:{} ---".format(child.tag, child.attrib, child.text))

    # 遍历root元素及其所有子元素
    for child in root.iter():
        print("---tag:{}, attr:{}, txt:{} ---".format(child.tag, child.attrib, child.text))

    # 遍历root下指定标签的所有子元素
    for neighbor in root.iter('neighbor'):
        print("neighbor: {}".format(neighbor.attrib))

    # 遍历root下 country 标签的所有一级子元素。
    for country in root.findall('country'):
        name = country.get('name')
        # 获取country下第一个 rank 标签的子元素
        rank = country.find('rank').text
        print("country name: {}, rank: {}".format(name, rank))

    # 更新xml
    for rank in root.iter('rank'):
        new_rank = int(rank.text) + 1
        # 直接修改字段
        rank.text = str(new_rank)
        # 添加或修改属性
        rank.set('updated', 'yes')
        print("rank:{}".format(rank.text))

    tree.write('output.xml')


if __name__ == '__main__':
    main()
<?xml version="1.0"?>
<data>
    <country name="Liechtenstein" ag="adf">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
        <rank>100</rank>
        <country>test</country>
    </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>
    <country1 name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country1>
</data>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值