Phillip Stack
Phillip Stack

Reputation: 3378

ElementTree (xml.etree) Parsing XML

Having trouble parsing this xml. Can anyone enlighten me on how it should be done?

Here is what I have tried.

XML (test.xml)

<?xml version="1.0" ?>
<element xmlns="http://yoursite.com/">
    <hello>
        <world>1</world>
        <world>2</world>
        <world>3</world>
        <world>4</world>
    </hello>
</element>

PYTHON

import xml.etree.ElementTree as ET

with open("test.xml",'r') as f:
    tree = ET.parse(f)

for node in tree.findall('.//element/hello/world'):
    print node.text

When I run this python I get absolutely nothing. Please be kind, as I imagine this should be incredibly simple.

Upvotes: 0

Views: 207

Answers (1)

AChampion
AChampion

Reputation: 30288

All these tags live under a namespace (xmlns="http://yoursite.com/"). So you need either prefix the search with this namespace or create a alias mapping, e.g.:

>>> ns = {'myns': 'http://yoursite.com/'}
>>> for node in tree.findall(('./myns:hello/myns:world'), ns):
...     print(node.text)
1
2
3
4

Note: . is your root node so myns:element would not find anything (you have no element under your root).

The search without the alias would look like:

for node in tree.findall(('./{http://yoursite.com/}hello/{http://yoursite.com/}world')):

Upvotes: 1

Related Questions