如何用XSLT为最近PI后的元素添加属性直至遇到下一个PI
问题解决:基于前置处理指令(PI)为XML元素添加属性
需求说明
检查所有XML元素,判断其是否存在前置(无需是兄弟节点)的处理指令(PI)。若存在,需为该PI之后的所有元素添加属性,直至遇到下一个PI为止。
示例XML输入
<chapter id = "1"> <section> <heading>some text here</heading> <p>some text here<?Test1?></p> </section> <section> <heading>some text here</heading> <p>some text here<?Test2?></p> </section> </chapter> <chapter id="2"> <section> <p></p> </section> </chapter>
预期结果
id为"2"的chapter元素仅添加test2属性,不应添加test1属性。
当前问题
原有XSLT代码会同时为该chapter元素添加test1和test2属性,不符合预期。
最终解决方案
参考Michael Kay的思路后,编写了可行的XSLT模板。通过获取元素的最近前置PI(即preceding::processing-instruction()[1]),为元素添加对应属性,精准实现需求:
<xsl:template match="*"> <xsl:copy> <xsl:copy-of select="@*"/> <xsl:variable name="piParent" select="preceding::processing-instruction()[1]"/> <xsl:if test="$piParent"> <xsl:attribute name="processPI"> <xsl:value-of select="name($piParent)"/> </xsl:attribute> </xsl:if> <xsl:apply-templates/> </xsl:copy> </xsl:template>
内容的提问来源于stack exchange,提问作者Chris G
相关产品推荐
相关产品推荐

