簡體   English   中英

獲取 XSLT Python 中給定元素的 xpath

[英]Get xpath of a given element in XSLT Python

我正在嘗試搜索一個元素並將完整的 xpath 返回到 XSLT 中的該元素。

例如,我有一個 XSLT 文件,如下所示:

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

我正在尋找可以解析 XSLT 文件的 function 文件,輸入如下內容:

info1

並返回:

title/header/info1

如果帶有該標簽的元素不止一個,那么我想返回所有元素。

我已經嘗試過這里這里建議的方法,但它們似乎不起作用。 任何幫助將不勝感激,謝謝!

如果您想通過 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>&#10;</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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM