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

python xml解析之 xml.etree.ElementTree

时间:2018-03-08 10:40:37      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:print   XML   country   sub   1.0   parse   ppc   body   解析   

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

标签:print   XML   country   sub   1.0   parse   ppc   body   解析   

原文地址:https://www.cnblogs.com/alplf123/p/8526736.html

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