Xml 对标记的参数进行xslt测试
我想在xslt中创建一个模板,并对匹配的标记的参数设置一个条件 例如: 如果我有标签Xml 对标记的参数进行xslt测试,xml,xslt,xsl-fo,Xml,Xslt,Xsl Fo,我想在xslt中创建一个模板,并对匹配的标记的参数设置一个条件 例如: 如果我有标签和 我想创建如下模板: <xsl:template match="par"> <xsl:if test="class=class1"> <fo:block space-before="3pt" space-after="3pt"> <xsl:apply-templates /> </fo:block> </x
和
我想创建如下模板:
<xsl:template match="par">
<xsl:if test="class=class1">
<fo:block
space-before="3pt"
space-after="3pt">
<xsl:apply-templates />
</fo:block>
</xsl:if>
<xsl:otherwise>
<fo:block
space-before="10pt"
space-after="10pt">
<xsl:apply-templates />
</fo:block>
</xsl:otherwise>
</xsl:template>
但它不起作用。如何测试标签的参数
提前感谢。您可以使用@访问属性,并可以按如下方式测试属性的值:
<xsl:if test="@class = 'class1'">
....
</xsl:if>
....
或者使用检查属性是否存在
<xsl:if test="@class">
...
</xsl:if>
...
这些“参数”的技术术语是“属性”(以防万一,有助于将来的搜索),您可以使用@class
等来引用它们
还要注意,
不是用于
,而是用于
:
<xsl:template match="par">
<xsl:choose>
<xsl:when test="@class='class1'">
<fo:block
space-before="3pt"
space-after="3pt">
<xsl:apply-templates />
</fo:block>
</xsl:when>
<xsl:otherwise>
<fo:block
space-before="10pt"
space-after="10pt">
<xsl:apply-templates />
</fo:block>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
或者,为了更好地显示实际的差异
<xsl:template match="par">
<fo:block>
<xsl:choose>
<xsl:when test="@class='class1'">
<xsl:attribute name='space-before'>3pt</xsl:attribute>
<xsl:attribute name='space-after'>3pt</xsl:attribute>
</xsl:when>
<xsl:otherwise>
<xsl:attribute name='space-before'>10pt</xsl:attribute>
<xsl:attribute name='space-after'>10pt</xsl:attribute>
</xsl:otherwise>
</xsl:choose>
<xsl:apply-templates/>
</fo:block>
</xsl:template>
3pt
3pt
10磅
10磅
首先
是“独立”指令。如果在默认情况下需要,可以使用xsl:choose
在代码中,xsl:if测试xpath是否无效。属性访问使用@attribute\u name
,字符串文本使用单引号
固定代码:
<xsl:template match="par">
<xsl:choose>
<xsl:when test="@class = 'class1'">
<fo:block
space-before="3pt"
space-after="3pt">
<xsl:apply-templates />
</fo:block>
</xsl:when>
<xsl:otherwise>
<fo:block
space-before="10pt"
space-after="10pt">
<xsl:apply-templates />
</fo:block>
</xsl:otherwise>
<xsl:choose>
</xsl:template>
但对于您的任务,还有更优雅的解决方案:
<xsl:template match="par">
<fo:block
space-before="10pt"
space-after="10pt">
<xsl:if test="@class = 'class1'">
<xsl:attribute name="space-before" select="'3pt'"/>
<xsl:attribute name="space-after" select="'3pt'"/>
</xsl:if>
<xsl:apply-templates />
</fo:block>
</xsl:template>
您实际上可以使用不同的模板,而不是使用
。像这样:
<xsl:template match="par[@class='class1']">
..
</xsl:template>
<xsl:template match="par">
..
</xsl:template>
..
..
第二个模板用于第一个模板不匹配的任何
par
元素。尽管第二个模板可以匹配所有par
元素,但它会被第一个模板覆盖,因为后者更具体。属性引号有误:
`实际上,你们都错了;只要不使用相同的引号,用来括起属性值的引号和其中的字符串值实际上是可以互换的。答案的真正问题是test
子句没有将class1
值括在引号中。顺便说一句,在xslt1中,您不能在
上使用select
,只有XSLT2可以这样做。如果您学会了这些术语,您会发现更容易获得答案(无论是在这里还是从书籍和在线搜索中)。您谈论的是元素和属性,而不是标记和参数。