栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用ElementTree递归遍历Python中的XML标签?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用ElementTree递归遍历Python中的XML标签?

要遍历所有节点,请在ElementTree而不是根Element上使用iter方法。

根是一个元素,就像树中的其他元素一样,并且实际上仅具有其自己的属性和子元素的上下文。ElementTree具有所有Elements的上下文。

例如,给定此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>

您可以执行以下操作

>>> import xml.etree.ElementTree as ET>>> tree = ET.parse('test.xml')>>> for elem in tree.iter():...     print elem... <Element 'data' at 0x10b2d7b50><Element 'country' at 0x10b2d7b90><Element 'rank' at 0x10b2d7bd0><Element 'year' at 0x10b2d7c50><Element 'gdppc' at 0x10b2d7d10><Element 'neighbor' at 0x10b2d7e90><Element 'neighbor' at 0x10b2d7ed0><Element 'country' at 0x10b2d7f10><Element 'rank' at 0x10b2d7f50><Element 'year' at 0x10b2d7f90><Element 'gdppc' at 0x10b2d7fd0><Element 'neighbor' at 0x10b2db050><Element 'country' at 0x10b2db090><Element 'rank' at 0x10b2db0d0><Element 'year' at 0x10b2db110><Element 'gdppc' at 0x10b2db150><Element 'neighbor' at 0x10b2db190><Element 'neighbor' at 0x10b2db1d0>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/634106.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号