Friday, 20 November 2015

XML : Python lxml: How to traverse back up a tree

i have the following python code

  import lxml.etree    root = lxml.etree.parse("../../xml/test.xml")    path="./pages/page/paragraph[contains(text(),'ash')]"  para = root.xpath(path)    

once i reach the para node, i dont want to go any further. Now i want to travel back up to the root and look at all of the <paragraph> nodes. Is there a way to travel back up the tree.

Or look at it this way. I want the subtree between root and para. How would i do that?

For reference, here is the xml

  <document>      <pages>        <page>            <paragraph>XBV</paragraph>           <paragraph>GFH</paragraph>      </page>        <page>         <paragraph>ash</paragraph>           <paragraph>lplp</paragraph>      </page>        </pages>  </document>    

now in this case, i want the nodes XBV and GFH. How is that possible?

No comments:

Post a Comment