zoukankan      html  css  js  c++  java
  • [python 学习] 使用 xml.etree.ElementTree 模块处理 XML

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

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

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

  • 相关阅读:
    Docker的安装、配置及其基本使用
    Java提升七:注解
    Java提升六:泛型
    Java提升五:反射与动态代理
    MySQL中如何将主键默认值设为UUID()
    图解Mybatis框架原理及使用
    Java提升四:Stream流
    Java提升三:函数式接口
    Java提升二:Lambda表达式与方法引用
    java提升一:内部类
  • 原文地址:https://www.cnblogs.com/natian-ws/p/7523589.html
Copyright © 2011-2022 走看看