XSLT:测试节点是否存在,无论它是当前节点的子节点还是孙节点
我正在处理一些 xslt 转换,我刚刚发现我当前的父级和它的子级之间可能存在也可能没有额外的节点,具体取决于外部因素。所以现在我必须更改我的 xslt 代码才能处理这两种情况:
场景 1:
<parent>
<child/>
<child/>
<parent>
场景 2:
<parent>
<nuisance>
<child/>
<child/>
</nuisance>
<parent>
我在某些情况下 test="parent/child"
或以其他方式使用此格式访问父节点/节点。
我需要类似 test="parent/magic(* or none)/child"
他们知道可以解决这个问题的唯一方法是使用:
<xsl:choose>
<xsl:when test="parent/child">
<!-- select="parent/child"-->
</xsl:when>
<xsl:otherwise>
<!-- select="parent/*/child"-->
</xsl:otherwise>
</xsl:choose>
但这将使我的代码大小增加三倍并且将需要大量的体力劳动...
非常感谢帮助!
I'm working on some xslt transformations and I've just found out that there might or might not be an extra node between my current parent and it's clildren, depending on external factors. So now I have to change my xslt code in order to deal with both of these scenarios:
scenario 1:
<parent>
<child/>
<child/>
<parent>
scenario 2:
<parent>
<nuisance>
<child/>
<child/>
</nuisance>
<parent>
I have situations in which I test="parent/child"
or otherwise use this format of accessing a parent/node.
I need something like test="parent/magic(* or none)/child"
They only way I know of that can solve this problem is to use:
<xsl:choose>
<xsl:when test="parent/child">
<!-- select="parent/child"-->
</xsl:when>
<xsl:otherwise>
<!-- select="parent/*/child"-->
</xsl:otherwise>
</xsl:choose>
But this will triple my code in size and will be a lot of manual labour...
Help much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不简单地选择两者的并集呢?
这将在两种情况下选择正确的节点。
Why not simply select the union of the two?
This will select the correct nodes in both cases.
这个表达式可能更快:
比表达式:
几乎所有 XPath 引擎都会在第一次出现
parent/child
或第一次出现parent/someElement/child
时立即停止计算另一方面,第二个表达式选择所有元素的并集
parent/child
和parent/*/child
元素,并且可能有很多这样的元素。更糟糕的是:
原始问题所需的测试与在与该测试匹配的所有节点上应用模板有很大不同。仅测试某个条件即可显着提高效率。 OP 没有以任何方式表明测试以任何方式与应用模板相关。
This expression may be faster:
than the expression:
Almost any XPath engine will immediately stop the evaluation at the first occurence of
parent/child
or at the first occurence ofparent/someElement/child
On the other side, the second expression selects the union of all
parent/child
andparent/*/child
elements and there may be many such elements.Even worse is:
A test, as the original question needs, is very different from applying templates on all nodes that match this test. Just testing for a condition can be significantly more efficient. The OP hasn't indicated in any way that the test is in any way connected to applying templates.