[英]Get xpath of a given element in XSLT Python
如果您想通過 XSLT 執行此操作,請嘗試以下操作:
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> </xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
使用 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.