如何在XSLT样式表中筛选后接@pc的指定@phr元素?
解决方法:匹配特定属性且后紧跟句号
<pc>的<phr>元素 要实现这个需求,核心是用XPath的following-sibling轴定位目标<phr>的下一个兄弟节点,同时结合属性条件过滤。下面是完整的实现方案:
1. 示例XML结构
假设你的XML文档结构类似这样:
<root> <phr function="inciso" type="absolute">需要提取的内容</phr> <pc>.</pc> <!-- 紧跟句号,符合条件 --> <phr function="inciso" type="absolute">不需要提取的内容</phr> <pc>,</pc> <!-- 不是句号,不符合条件 --> <phr function="inciso" type="relative">其他类型</phr> <pc>.</pc> <!-- 属性不匹配,不符合条件 --> </root>
2. 对应的XSLT样式表
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" encoding="UTF-8"/> <!-- 匹配符合条件的phr元素 --> <xsl:template match="phr[@function='inciso' and @type='absolute' and following-sibling::*[1][self::pc and text()='.']]"> <!-- 提取phr的文本内容,你可以根据需求修改输出格式 --> <xsl:value-of select="text()"/> <xsl:text> </xsl:text> <!-- 换行分隔结果 --> </xsl:template> <!-- 忽略其他节点,避免输出无关内容 --> <xsl:template match="text()|@*"/> </xsl:stylesheet>
3. 关键XPath表达式解释
让我们拆解一下核心的匹配条件:
phr[@function='inciso' and @type='absolute']:首先筛选出拥有指定属性的<phr>元素following-sibling::*[1]:定位该<phr>的第一个后续兄弟节点(确保是紧跟在后面的元素)[self::pc and text()='.']:检查这个兄弟节点必须是<pc>元素,且其文本内容是句号
4. 扩展说明
如果你的<pc>元素可能包含空白字符(比如<pc> . </pc>),可以用normalize-space()来处理,确保匹配更精准:
phr[@function='inciso' and @type='absolute' and following-sibling::*[1][self::pc and normalize-space(text())='.']]
这样就能精准提取所有符合条件的<phr>元素内容了!
内容的提问来源于stack exchange,提问作者Miguel Las Heras




