6

I am often working with quite complex documents that I am effectively reverse engineering. I need to write code to modify the value of certain nodes with the path traversed to reach the node acting as a condition.

When examining the XML data to understand it's structure, it would be very useful to have a representation on of this path. I can then use the path in the code to get to that specific node.

For example, I can get the representation Catalog > Book > Textbook > Author from the document below.

Are there any libraries in Python that allows me to do this?

<xml>
    <Catalog>
        <Book>
            <Textbook>
                <Author ="James" />
            </Textbook>
        </Book>
        <Journal>
            <Science>
                <Author ="James" />
            </Science>
        </Journal>
    </Catalog>
</xml>
3
  • 2
    Do you mean you would like a way to point at a node and find out an XPath to that node? Commented Nov 12, 2012 at 21:12
  • I know, it's not python but, if you need a quick way to parse an xml and get the XPath expression of a node try this nice online xml editor: xmlgrid.net ... just right-click on a node and select "Show XPath" Commented Nov 12, 2012 at 22:02
  • thanks that editor is perfect. Commented Nov 12, 2012 at 22:24

1 Answer 1

7

The lxml library has a etree.Element.getpath method (search for Generating XPath expressions in the previous link) "which returns a structural, absolute XPath expression to find that element". Here's an example from the lxml library documentation:

>>> a  = etree.Element("a")
>>> b  = etree.SubElement(a, "b")
>>> c  = etree.SubElement(a, "c")
>>> d1 = etree.SubElement(c, "d")
>>> d2 = etree.SubElement(c, "d")

>>> tree = etree.ElementTree(c)
>>> print(tree.getpath(d2))
/c/d[2]
>>> tree.xpath(tree.getpath(d2)) == [d2]
True
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.