简体   繁体   中英

xml traversal in python

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.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM