Holden
Holden

Reputation: 23

Get xpath of a given element in XSLT Python

I am trying to search for an element and return the full xpath to that element in XSLT.

For example, I have an XSLT file like this:

<title>
  <header>
    <info1>A</info1>
    <info2>B</info2>
  </header>
</title>

I'm looking for a function where I can parse the XSLT file, enter something like:

info1

and return:

title/header/info1

If there is more than one element with that tag, then I want to return all of them.

I've tried the methods suggested here and here but they don't seem to work. Any help would be appreciated, thanks!

Upvotes: 0

Views: 254

Answers (2)

balderman
balderman

Reputation: 23815

Using lxml

from lxml import etree

xml = '''<title>
  <header>
    <info1>A</info1>
    <info2>B</info2>
    <jack>
        <info1>AA</info1>
    </jack>
  </header>
</title>'''

root = etree.fromstring(xml)
tree = etree.ElementTree(root)
elements = root.findall('.//info1')
for e in elements:
    print(tree.getpath(e))

output

/title/header/info1
/title/header/jack/info1

Upvotes: 2

michael.hor257k
michael.hor257k

Reputation: 116992

If you want to do this through XSLT, try something like:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:param name="element-name">info1</xsl:param>

<xsl:template match="/">
    <xsl:for-each select="//*[name()=$element-name]">
        <xsl:for-each select="ancestor-or-self::*">
            <xsl:value-of select="name()"/>
            <xsl:if test="position() != last()">
                <xsl:text>/</xsl:text>
            </xsl:if>
        </xsl:for-each>    
        <xsl:text>&#10;</xsl:text>
    </xsl:for-each>   
</xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions