如果以下问题看起来很愚蠢,请抱歉,但由于我缺乏经验,我无法确定此方法的可靠性。
我正在尝试使用 XSLT 1.0 为自己构建一个 XPath 1.0 位置路径评估器。
这个想法很简单。该转换接收 xpath 表达式的输入进行计算,然后将模板应用到选定的节点。为每种节点定义了一个模板,以在输出上复制节点(以及更多信息)。显然,输入文档将使用 XSLT 1.0 兼容处理器进行转换。
根据您的专业知识,我想知道的是,这种方法是否是绝对、可靠且可靠的测试位置路径和显示所选位置的方法节点集。我并不是要求有人调试我的代码。我已经针对各种输入文档进行了测试,它似乎工作正常。我想知道从 XPath 的角度来看我是否遗漏了一些东西。
这可以与任何 XPath 1.0位置路径一起正常工作吗?
这是否仅限于 XPath 1.0/XSLT 1.0?我不认为仅通过更改其版本(显然还有 XSLT 处理器)来将模板扩展到 XPath 2.0 有任何禁忌。
这是应该用作 XPath 测试器的转换。注意:
- 我省略了注释和 pi 节点的模板,以使转换不会太繁重,但它们目前以类似的方式进行管理。
- 目前不需要管理命名空间。
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="path-expr" select="*"/>
<xsl:template match="/">
<xpath-tester>
<node-sets count="{count($path-expr)}">
<xsl:apply-templates select="$path-expr" mode="path-expr"/>
</node-sets>
</xpath-tester>
</xsl:template>
<xsl:template match="node()|@*" mode="path-expr">
<node-set
position="{position()}"
id="{generate-id()}"
parent-id="{name(parent::*[1])}-{generate-id(parent::*[1])}">
<xsl:apply-templates select="." mode="output"/>
</node-set>
</xsl:template>
<xsl:template match="*" mode="output">
<xsl:attribute name="type">element</xsl:attribute>
<node>
<xsl:copy-of select="."/>
</node>
</xsl:template>
<xsl:template match="@*" mode="output">
<xsl:attribute name="type">attribute</xsl:attribute>
<node>
<xsl:copy-of select="."/>
</node>
</xsl:template>
<xsl:template match="text()" mode="output">
<xsl:attribute name="type">text</xsl:attribute>
<node>
<xsl:copy-of select="."/>
</node>
</xsl:template>
</xsl:stylesheet>
最佳答案
听起来类似于我的一个宠物项目;请随意查看我的代码,它太大了,无法粘贴到此处:
http://www.flynn1179.net/xml/FullDisplayXml.xslt
它将任何 XML 文档转换为具有可折叠节点的 html 页面,并且通过修改顶部附近键的“match”属性,您可以指定节点的 XPath,并让它生成节点列表或突出显示它们在源代码中。
我在这里问了一个与此非常相似的问题:How can you pass in a parameter to an xslt that can be used in a xsl:key? ,尽管我试图将参数应用于 key ,但这不起作用。
注意:该代码是一项正在进行的工作,它在某些地方有点丑陋,我相当确定它没有正确处理一些事情,或者可以做得更好,但希望它有用。我在我的 XML 沙箱页面上使用它的衍生版本:http://www.flynn1179.net/xml/ (这也是一项正在进行的工作,我知道其中存在一些错误)
关于xpath - XSLT 1.0 转换可以用作纯 XPath 1.0 位置路径评估器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6508597/