3

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?

2
  • Asking for how to set a specific great-great-...-grand child element "as the root element" does not really make sense to me. Your XML file has one root element. There cannot be more than one. Do you in fact want to find a particular descendant element without having to keep the whole XML structure in memory? Commented Jan 18, 2015 at 10:29
  • That is exactly what I wanted. I would like to find that node and start to iterate from it like it was the root element. Plus it would better the readability of the code not to have ten cycles before starting any real work on the structure. Commented Jan 18, 2015 at 11:55

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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'):
    ...

1 Comment

Pfoe you really saved my day. I've been looking for this solution for hours...Why did they make it so unclear and hard to find...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.