检索在Python中具有标签-XML的元素



从下面的样本xml

<?xml version="1.0"?>
    <data>
        <country>
            <name>Liechtenstein</name>
            <rank>1</rank>
            <year>2008</year>
            <gdppc>141100</gdppc>
            <neighbor name="Austria" direction="E"/>
            <neighbor name="Switzerland" direction="W"/>
        </country>
        <country>
            <name>Singapore</name>
            <rank>4</rank>
            <year>2011</year>
            <gdppc>59900</gdppc>
            <neighbor name="Malaysia" direction="N"/>
        </country>
        <country>
            <name>Panama</name>
            <rank>68</rank>
            <year>2011</year>
            <gdppc>13600</gdppc>
            <neighbor name="Costa Rica" direction="W"/>
            <neighbor name="Colombia" direction="E"/>
        </country>
    </data>

使用Python ElementTree

import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')

for elem in tree.iter(tag='name'):
    print (elem.tag)

显示三个名称元素。我如何只用特定的文本检验一个名称元素 <name>Panama</name>

for elem in tree.iter(tag="name='panama'"):不起作用

您可以考虑在lxml中使用xpath。使用text()使您可以快速找到"巴拿马"作为元素的内容。完成后,您可以导航到同一国家的相邻信息项。

>>> from lxml import etree
>>> tree = etree.parse('test.xml')
>>> tree.xpath('.//name/text()')
['Liechtenstein', 'Singapore', 'Panama']
>>> for item in tree.xpath('.//name/text()'):
...     if item == 'Panama':
...         for cousins in item.getparent().getparent().getchildren():
...             cousins.text
...             
'Panama'
'68'
'2011'
'13600'
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
countries = tree.findall("country")
for country in countries:
    name = country.find("name")
    if name.text == "Panama":
        print(name.text)

另外,请注意,您的XML表现不佳。您有一个],而不是>在test.xml

的第19行中

相关内容

  • 没有找到相关文章

最新更新