1

I have an xml file of the following form:

<Op Id="Op_Join" I="14">
    <Op Id="Op_Sort" I="1">                                                      
        <Op Id="Op_Join" I="2">
             <Op Id="Op_Exchange" I="11">                                                          
                   <Op Id="Op_Extract" I="5">                                                            
                   </Op>
             </Op>
        </Op>
    </Op>
</Op>

Now I want to traverse this xml file in a bottom-up manner. That is, starting from the bottom "Op_Extract". I want to find the first "Op_Join" that it comes across while traversing from bottom to top. In the example xml file above the first "Op_Join" has I="2".

I know I can use "xml.etree.ElementTree" in python to traverse the xml file in a top-down manner. However I am looking for a way to traverse the xml file in a bottom-up manner.

The xml document that I have can be arbitrarily complex. The snippet pasted here is just for exposition.

1 Answer 1

1

Not quite traversing in reverse (although I don't see why that couldn't be possible), but for the problem described you can use xpath to get the nodes that match your criteria, it should order them according to how the document is laid out and should be able to grab the last one.

## parsing data.
In [18]: from lxml import etree

In [19]: x = """
    ...: <Op Id="Op_Join" I="14">
    ...:     <Op Id="Op_Sort" I="1">
    ...:         <Op Id="Op_Join" I="2">
    ...:              <Op Id="Op_Exchange" I="11">
    ...:                    <Op Id="Op_Extract" I="5">
    ...:                    </Op>
    ...:              </Op>
    ...:         </Op>
    ...:     </Op>
    ...: </Op>"""

### creating an lxml object using etree:

In [20]: x = etree.fromstring(x)

In [21]: [e.get('I') for e in x.xpath('//Op[@Id="Op_Join"]')][-1]
Out[21]: '2'
Sign up to request clarification or add additional context in comments.

Comments

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.