Getting The Path Of An Xml Node In Python
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 rea
Solution 1:
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
Post a Comment for "Getting The Path Of An Xml Node In Python"