只获取 xpath 的最后一部分

Get only last part of xpath

我在 python 2.7 中使用 lxml 来解析 xml 文件。

文件如下所示:

...
<LM>sua</LM>
<LM>citt&agrave;</LM>
<LM>e</LM>
<LM>l'</LM>
<LM>alto</LM>
<LM>seggio</LM>:
     </l><l>
<LM>oh</LM>
<LM>felice</LM>
<LM>colui</LM>
<LM>cu'</LM>
<LM>ivi</LM>
<LM>elegge</LM>!.
     </l><l>
<LM> E</LM>
<LM>io</LM>
<LM>a</LM>
<LM>lui</LM>:
...

我正在遍历树以寻找 LM 节点。

for node in [z for z in  tree.iterfind(".//LM")]:
    print tree.getpath(node.getparent())

我得到每个节点的以下输出:

'/TEI.2/text/body/div1/l[480]'

所以,在这种情况下,这意味着当前节点 LM 在第 480 个节点 L 下。有没有办法得到这个 480,请注意以下内容?

In [77]: int(tree.getpath(node.getparent()).split('/')[5][2:].replace(']',''))
Out[77]: 480

我的意思是通过 xpath 的优雅方式。

So, in this case this means the the current node LM is under the 480th node L. Is there a way to get this 480 that is note the following ?

int(tree.getpath(node.getparent()).split('/')[5][2:].replace(']',''))

如果我没理解错的话,你只是想要相对于父级的位置?您可以通过执行以下操作使 XPath return 最后一个位置:

node.find("position()")

在正常的 XPath 1.0 中,这意味着 "get the position of the current node relative to its parent"。但是,它看起来像XPath support of this Python module is severely limited。支持的表达式只能用于 return 节点而不是值。

If you can use XSLT in Python,您可以使用 XPath 1.0 语法 //LM/position() 获取所有位置。为了获得路径,你还需要做更多的事情:

<xsl:template match="/">
    <xsl:apply-templates select="//LM" />
</xsl:template>

<xsl:template match="LM">
    <xsl:text>Position: </xsl:text>
    <xsl:value-of select="position()" />
    <xsl:text>, XPath: </xsl:text>
    <xsl:apply-templates select="ancestor::*" mode="path" />
    <xsl:text>&#xA;</xsl:text>
</xsl:template>

<xsl:template match="*" mode="path">
    <xsl:text>/</xsl:text>
    <xsl:value-of select="name()" />
</xsl:template>

这将输出一堆行,如:

Position: 4, XPath: /a/b/c
Position: 9, XPath: /a/b/d