Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML parsing: set great-great-...-grandchild element as a root in Python

I have a XML file which has structure like this:

<element1>
    <element2>
        ...
        <element10 name="a">
            ...

I am trying to parse this file in Python 2.7, using The ElementTree XML API. But the data I am looking for are deeply hidden in the structure.

Is there any way I can set specific great-great-...-grand child element (for example the element10) as the root element without iterating the whole structure?

like image 930
katenoox Avatar asked Dec 11 '25 11:12

katenoox


2 Answers

Try this :

'(//*[starts-with(name(), "element")])[last()]'

DEMO :

$ cat file
<element1>
    <element2></element2>
    <element3></element3>
    <element4></element4>
    <element5></element5>
    <element6></element6>
    <element10 name="a">x</element10>
</element1>

CODE :

(works with xmllint too)

$ saxon-lint.pl --xpath '(//*[starts-with(name(), "element")])[last()]' file

OUTPUT:

<element10 name="a">x</element10>
like image 195
Gilles Quenot Avatar answered Dec 14 '25 00:12

Gilles Quenot


I have finally solved it thanks to this great article.

tree.iter(tag = 'element10')

This will find the needed element in the structure and then you can iterate his child elements, even if there are more 'element10' named elements in the tree.

for element in tree.iter(tag = 'element10'):
    ...
like image 34
katenoox Avatar answered Dec 14 '25 01:12

katenoox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!