XSLT1.0中如何编写XPath筛选指定路径下的前置堂兄弟节点
解决方案
核心思路
给preceding/following轴增加路径筛选规则:仅保留父节点为root直接子节点house的occupant节点,排除嵌套在其他层级下的同类节点即可满足需求。
对应XPath表达式
1. 统计符合要求的前置节点数量
将原统计语句替换为:
count(preceding::occupant[../parent::root])
2. 提取最近的前置/后置符合要求的节点
对应补充需求的提取逻辑,替换为:
<!-- 取最近的前置符合要求的节点 --> (preceding::occupant[../parent::root])[1] <!-- 取最近的后置符合要求的节点 --> (following::occupant[../parent::root])[1]
原理说明
preceding::occupant会按文档顺序返回当前节点之前所有的occupant节点- 谓词
[../parent::root]筛选出父节点(house)的父节点是root的节点,正好匹配你需要的/root/house/occupant路径规则,自动排除了嵌套在next_door下的occupant节点 - 以上语法均为XPath 1.0标准特性,完全兼容XSLT 1.0运行环境
完整修改后代码示例
统计数量版本
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" > <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <counts> <xsl:apply-templates select="root/house/occupant"/> </counts> </xsl:template> <xsl:template match="occupant"> <previous> <xsl:value-of select="count(preceding::occupant[../parent::root])"/> </previous> </xsl:template> </xsl:stylesheet>
提取前后节点版本
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" > <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <counts> <xsl:apply-templates select="root/house/occupant"/> </counts> </xsl:template> <xsl:template match="occupant"> <previous_and_next> <previous> <xsl:copy-of select="(preceding::occupant[../parent::root])[1]"/> </previous> <next> <xsl:copy-of select="(following::occupant[../parent::root])[1]"/> </next> </previous_and_next> </xsl:template> </xsl:stylesheet>
内容的提问来源于stack exchange,提问作者MrD at KookerellaLtd
相关产品推荐
相关产品推荐

