Sigma
Sigma

Reputation: 121

Parsing XML with ElementTree's iter() isn't finding my tags when I pass a specific argument

Trying to return attribute & values from a tag. Following the ElementTree documentation to word for word is producing nothing. No errors, it just runs and doesn't print anything. If I run iter() with no arguments it prints every single tag, but with an argument it does nothing. Not sure what's going on. The findall() doesn't work either.

If I use the doc's XML it works fine, but not with mine. Only difference I see are tags closed in the same bracket for the doc XML.

I'm using the right version of Python without a doubt, so i'm at a loss. Below is my XML first, Doc XML 2nd, and the code to run it.

<?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)

Upvotes: 3

Views: 2092

Answers (1)

Daniel Haley
Daniel Haley

Reputation: 52888

Your first XML has a default namespace of x-schema:..\schema_ej.xml.

Try changing your iter() to this instead:

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

See here for more info on namespaces in ElementTree.

See here for more info on XML namespaces in general.

Upvotes: 2

Related Questions