【问题标题】:Parsing XML with ElementTree's iter() isn't finding my tags when I pass a specific argument当我传递特定参数时,使用 ElementTree 的 iter() 解析 XML 时找不到我的标签
【发布时间】:2019-04-12 15:36:11
【问题描述】:

试图从标签返回属性和值。逐字逐句地遵循 ElementTree 文档并没有产生任何结果。没有错误,它只是运行并且不打印任何内容。如果我在没有参数的情况下运行 iter(),它会打印每个标签,但如果有参数,它什么也不做。不知道发生了什么。 findall() 也不起作用。

如果我使用文档的 XML,它可以正常工作,但不适用于我的。我看到的唯一区别是标记在文档 XML 的同一个括号中。

毫无疑问,我使用的是正确版本的 Python,所以我很茫然。下面是我的 XML 第一个,Doc XML 第二个,以及运行它的代码。

<?xml version="1.0" encoding="iso_8859-1"?>
<day xmlns="x-schema:..\schema_ej.xml" FILE="90301007.009">
<trs F1068="SALE" F254="2019-03-01" F253="2019-03-01T12:21:30" F1056="007" F1057="009" F1035="11:52:53" F1036="12:21:30"
F1032="74925" F1764="00074732" F1185="7110" F1126="7110" F1127="Eva S.">
<r F1101="1"><itm F01="0071834383234" F02="SI SSND SOUL 35Z" F04="30" F03="100" F81="1" F79="1" F1007="3.99" F1006="1" F1080="0.938"/><F65>3.99</F65><F64>1</F64><F1263>0.09</F1263><key in="1013" fn="10725"/><key in="1013" fn="10735"/><key in="1013" fn="10746"/><key in="1013" fn="10715"/><key in="1013" fn="10777"/><key in="1013" fn="10736"/><key in="1013" fn="10710"/><key in="1013" fn="10747"/><key in="1013" fn="10775"/><key in="1013" fn="10726"/><key in="1013" fn="10760"/><key in="1013" fn="10200"/><key fn="30"/><key in="71834383234" fn="710"/></r>
</trs>
</day>
<?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('90301007.xml')
root = tree.getroot()

for trs in root.iter('trs'):
    print(trs.attrib)

【问题讨论】:

    标签: python xml elementtree


    【解决方案1】:

    您的第一个 XML 的默认命名空间为 x-schema:..\schema_ej.xml

    尝试将您的 iter() 改为:

    root.iter(r'{x-schema:..\schema_ej.xml}trs')
    

    See here 了解有关 ElementTree 中命名空间的更多信息。

    See here 了解有关 XML 命名空间的更多信息。

    【讨论】:

    • 有趣的是,答案是向下滚动几卷。 XML 和 Python 的新手,所以这让我望而却步。谢谢,现在可以使用了。
    • 通常是 ;-) 不客气,欢迎来到 Stack Overflow!
    猜你喜欢
    • 2021-04-22
    • 2015-12-08
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 2011-10-11
    • 1970-01-01
    相关资源
    最近更新 更多