如何通过XSLT修改section-ref锚点的@href为父chunk的@id
Fixing XPath to Target Parent Chunk's ID for Section-Ref Anchors
我来帮你搞定这个XPath的问题,核心就是要精准定位到目标sect1元素的父chunk节点,然后提取它的@id值。咱们先梳理现有代码的问题,再给出完整的修正方案:
问题分析
你原来的$section变量只是返回一个布尔值(判断是否存在匹配的sect1),并没有选中对应的sect1元素,这就没办法后续获取它的父chunk。所以第一步要修正这个变量的选择逻辑,再通过选中的元素向上找到父chunk的@id。
修正后的XSLT代码
<!-- Identity template --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!--Change section-ref @href to parent chunk @id if they are @ids of a sect1--> <xsl:template match="a[@class='section-ref']"> <xsl:variable name="section-id" select="substring-after(./@href, '#')"/> <!-- 修正:选中匹配id的sect1元素,且该元素是chunk的子元素 --> <xsl:variable name="target-section" select="//div[@class='chunk']/div[@class='sect1'][@id=$section-id]"/> <xsl:choose> <xsl:when test="$target-section"> <xsl:copy> <!-- 关键XPath:通过sect1的父节点(chunk)获取id --> <xsl:attribute name="href" select="$target-section/../@id"/> <xsl:apply-templates select="(node() | @*) except @href"/> </xsl:copy> </xsl:when> <xsl:otherwise> <xsl:copy> <xsl:apply-templates select="node() | @*"/> </xsl:copy> </xsl:otherwise> </xsl:choose> </xsl:template>
关键代码解释
- 修正
$target-section变量:这个变量现在会直接选中匹配$section-id的sect1元素,并且限定该sect1必须是chunk的子元素,完全匹配你的需求场景。 - 获取父chunk的ID:
$target-section/../@id这个XPath的逻辑是:找到目标sect1的父节点(也就是chunk),然后提取它的@id值。 - 替换href属性:把原来的锚点
href替换成父chunk的id值,同时保留a标签的其他属性和文本内容。
测试验证
用你提供的XML示例运行这段XSLT后,会生成你期望的输出:
<book> <div> <p>In the <a class="section-ref" href="i100954" id="i2397">next section</a>, we turn lorem ipsum.</p> </div> <div class="extend" id="i100949"> <div class="check" id="i100950"> <h1 class="title">Check</h1> <a class="other-ref" href="folder/other-ref.xml" id="i100953"/> </div> </div> <div class="chunk" id="i100954"> <h1 class="title">8.4</h1> <div class="other-section" id="i100955"> <p id="i100956"> Lorem Ipsum</p> </div> <div class="sect1" id="i2398"> <h1 class="title">Lorem Ipsum</h1> <p>Blah blah blah</p> </div> </div> </book>
可以看到section-ref锚点的href已经成功修改为父chunk的id(i100954),完全符合需求。
内容的提问来源于stack exchange,提问作者user2093335
相关产品推荐
相关产品推荐

