python xml解析之 xml.etree.ElementTree

Posted 我是外婆

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python xml解析之 xml.etree.ElementTree相关的知识,希望对你有一定的参考价值。

import xml.etree.ElementTree as tree
import io


xml = ‘‘‘<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
‘‘‘
parse = tree.fromstring(xml) #type:tree.Element #根节点
for e in parse: #遍历
    print(e.tag) # 节点名称
    print(e.attrib.get(name))#节点属性
result = parse.findall(country) # 只能找到子节点 第一层
print(result) #[<Element ‘country‘ at 0x0000000001DDE7C8>, <Element ‘country‘ at 0x000000000291F908>, <Element ‘country‘ at 0x000000000291FA98>]

print([e for e in parse.iter(rank) if e.attrib.get(updated) == yes]) #递归遍历所有

#父节点 parse 添加子节点
print(tree.SubElement(parse, test, attrib={name: ceshi})) #工厂方式添加子节点

print(tree.tostring(parse).decode(utf-8)) #输出xml文档

 

以上是关于python xml解析之 xml.etree.ElementTree的主要内容,如果未能解决你的问题,请参考以下文章

python xml解析之 xml.etree.ElementTree

python解析xml文件之xml.etree.cElementTree和xml.etree.ElementTree区别

人生苦短,我学python之python xml数据解析

Python 之lxml解析模块

python爬虫之html解析Beautifulsoup和Xpath

python模块之xml.etree.ElementTree