Python如何解析简单的xml文档

Jackey Python 1,495 次浏览 , 没有评论

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>

Python代码

# 如何解析简单的xml文档
from xml.etree.ElementTree import parse

f = open('demo.xml')

et = parse(f)
# 得到根节点
root = et.getroot()
print(root)
# 标签
print(root.tag)
# 字典
print(root.attrib)
print(root.text.strip())

# print(root.getchildren())

for child in root:
    print(child.get('name'))

# 总是找到第一个元素
print(root.find('country'))
# 找到所有, 返回列表
print(root.findall('country'))
# 返回可迭代对象
print(root.iterfind('country'))
for e in root.iterfind('country'):
    print(e.get('name'))

print(list(root.iter()))
print(list(root.iter('rank')))

# 匹配所有的子节点
print(root.findall('country/*'))

# // 描述找到任意层次下的子元素
print(root.findall('.//rank'))
# .. 描述父对象
print(root.findall('.//rank/..'))
# 描述包含某一个属性的
print(root.findall('country[@name]'))
# 描述属性为特定值的元素
print(root.findall('country[@name="Singapore"]'))
# 描述一个元素必须包含指定的子元素
print(root.findall('country[rank]'))
# 指定子元素的tag必须包含指定的值
print(root.findall('country[rank="5"]'))
# 指定相对位置
print(root.findall('country[1]'))
# 指定最后一个位置
print(root.findall('country[last()]'))
# 找倒数第二个
print(root.findall('country[last()-1]'))

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go