XSLT中如何输出当前元素路径? [英] How do you output the current element path in XSLT?
问题描述
在 XSLT 中,有没有办法在处理元素时确定您在 XML 文档中的位置?
In XSLT, is there a way to determine where you are in an XML document when processing an element?
示例:给定以下 XML 文档片段...
Example: Given the following XML Doc Fragment...
<Doc>
<Ele1>
<Ele11>
<Ele111>
</Ele111>
</Ele11>
</Ele1>
<Ele2>
</Ele2>
</Doc>
在 XSLT 中,如果我的上下文是元素Ele111",我怎样才能让 XSLT 输出完整路径?我希望它输出:/Doc/Ele1/Ele11/Ele111".
In XSLT, if my context is the Element "Ele111", how can I get XSLT to output the full path? I would want it to output: "/Doc/Ele1/Ele11/Ele111".
这个问题的上下文:我有一个非常大、非常深的文档,我想彻底遍历它(通常使用递归),如果我找到具有特定属性的元素,我想知道我在哪里找到它.我想我可以在遍历时沿着我当前的路径前进,但我认为 XSLT/XPath 应该知道.
The context of this question: I have a very large, very deep document that I want to traverse exhaustively (generically using recursion), and if I find an element with a particular attribute, I want to know where I found it. I suppose I could carry along my current path as I traverse, but I would think XSLT/XPath should know.
推荐答案
不要认为这是 XPath 内置的,您可能需要一个递归模板,例如 这里,我以此示例为基础.它将遍历 XML 文档中的每个元素,并以与您所描述的样式类似的样式输出该元素的路径.
Don't think this is built into XPath, you probably need a recursive template, like the one here, which I've based this example on. It will walk every element in an XML document and output the path to that element in a style similar to the one you've described.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
version="2.0">
<xsl:template match="/">
<paths>
<xsl:apply-templates/>
</paths>
</xsl:template>
<xsl:template match="//*">
<path>
<xsl:for-each select="ancestor-or-self::*">
<xsl:call-template name="print-step"/>
</xsl:for-each>
</path>
<xsl:apply-templates select="*"/>
</xsl:template>
<xsl:template name="print-step">
<xsl:text>/</xsl:text>
<xsl:value-of select="name()"/>
<xsl:text>[</xsl:text>
<xsl:value-of select="1+count(preceding-sibling::*)"/>
<xsl:text>]</xsl:text>
</xsl:template>
</xsl:stylesheet>
有一些并发症;考虑这棵树:
There are a few complications; consider this tree:
<root>
<child/>
<child/>
</root>
如何区分两个子节点?所以你需要一些索引到你的项目序列,child1和孩子[2],例如.
How do you tell the difference between the two child nodes? So you need some index into your item-sequence, child1 and child[2], for example.
这篇关于XSLT中如何输出当前元素路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!