我有以下XML:
<sections>
<sec id="1" sid="1">....</sec>
<sec id="2" sid="2">....</sec>
<sec id="3" sid="1">....</sec>
<sec id="4" sid="1">....</sec>
<sec id="5" sid="2">....</sec>
</sections>
<sec-list>
<s ref="1">.....</s>
<s ref="2">.....</s>
<s ref="3">.....</s>
</sec-list>
在XSLT中解析sec-list
时,我想检测所有sections/sec[@sid=@ref]
并提供指向每个单个标记的锚标记。例如:对于sec-list/s[@ref="1"]
,我想显示3个锚标记,这些锚标记指向具有sec
的3个@sid="1"
节点:
<div id="?">sec with id=1 and sid=1</div>
<div id="?">sec with id=3 and sid=1</div>
<div id="?">sec with id=4 and sid=1</div>
<a href="#?">sec with id=1 and sid=1</a>
<a href="#?">sec with id=3 and sid=1</a>
<a href="#?">sec with id=4 and sid=1</a>
我需要替换“?”具有唯一的ID,以后可以在“ href”中使用该ID进行指向。
答案 0 :(得分:2)
即使在XSLT-1.0中,也可以使用generate-id()
函数生成唯一的ID:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/root">
<xsl:apply-templates select="sec-list/s" mode="div" />
### Delimiter ###
<xsl:apply-templates select="sec-list/s" mode="href" />
</xsl:template>
<xsl:template match="sec-list/s" mode="div">
<xsl:variable name="ref" select="@ref" />
<xsl:for-each select="/root/sections/sec[@sid=$ref]">
<div><xsl:attribute name="id"><xsl:value-of select="generate-id()" /></xsl:attribute><xsl:value-of select="concat('sec with id=',@id,' and sid=',$ref)" /></div>
</xsl:for-each>
</xsl:template>
<xsl:template match="sec-list/s" mode="href">
<xsl:variable name="ref" select="@ref" />
<xsl:for-each select="/root/sections/sec[@sid=$ref]">
<a><xsl:attribute name="href"><xsl:value-of select="concat('#',generate-id())" /></xsl:attribute><xsl:value-of select="concat('sec with id=',@id,' and sid=',$ref)" /></a>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
其输出是:
<div id="idm3">sec with id=1 and sid=1</div>
<div id="idm5">sec with id=3 and sid=1</div>
<div id="idm6">sec with id=4 and sid=1</div>
<div id="idm4">sec with id=2 and sid=2</div>
<div id="idm7">sec with id=5 and sid=2</div>
###################
<a href="#idm3">sec with id=1 and sid=1</a>
<a href="#idm5">sec with id=3 and sid=1</a>
<a href="#idm6">sec with id=4 and sid=1</a>
<a href="#idm4">sec with id=2 and sid=2</a>
<a href="#idm7">sec with id=5 and sid=2</a>
注意:
$ref
代替了current()/@ref
,因为该值也在concat(..)
表达式中使用。#idmX
是指sections/sec
元素。<sections>
和<sec-list>
元素被包装在称为<root>
的根元素中。