【问题标题】:Unexplained behaviour of findall function in ElementTreeElementTree 中 findall 函数的无法解释的行为
【发布时间】:2014-02-12 15:24:06
【问题描述】:

我有以下有问题的代码:

import xml.etree.ElementTree as ET    

def main():
    tree = ET.parse('D:/Developer/Work/oDesk1/assets/test.xml')
    root = tree.getroot()
    print root.findall('.//country')

if __name__ == '__main__':
    main()

我有以下 XML:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="recipes.xsl"?>
<data xmlns="urn:Test" xmlns:xs="http://www.w3.org/2001/XMLSchema" name="Galaxy" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:Test test.xsd">
    <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>

问题:

root.findall('.//country') 返回一个空列表。

预期:

root.findall('.//country') 应该返回一个填充列表。

将 XML 数据更改为以下内容可以解决我的问题。

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="recipes.xsl"?>
<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>

我无法理解这种未定义的行为。我知道前面的 XML 指向一些 XML 模式。我想绕过 XML 模式信息而不编辑 XML 文件,以便在调用 root.findall() 函数时得到一个填充列表。我该怎么做?另外,请用两个略有不同的 XML 解释这种奇怪的行为。

【问题讨论】:

    标签: python xml xml-parsing elementtree


    【解决方案1】:

    etree 只是不能很好地处理命名空间。 您需要自己包含它,并使用它自己的语法:

    root.findall('.//{urn:Test}country')
    

    将返回预期的元素。

    findall 采用可选的命名空间参数,但它似乎不适用于“空”隐式命名空间

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多