gpt4 book ai didi

xslt - 如何根据 xslt 代码中的条件限制为标签添加属性

转载 作者:行者123 更新时间:2023-12-01 00:48:40 24 4
gpt4 key购买 nike

我们如何根据 xslt 中的某些条件创建属性。

我的输入 xml 有一个标签:

          <track external="http://mysite.com"  />
or
<track local="/myfolder" />

并且在这个'track元素中,出现了外部或本地属性,但没有出现任何一个,我必须将它转换成

       <a xhtml:href="@external value" xmlns="http://www.w3.org/1999/xhtml" /> 

如果 'track' 元素出现 'extrenal' 属性或进入

       <a xlink:href="@local value" xmlns="http://www.w3.org/1999/xlink" /> 

如果'track'元素出现'local'属性

XSLT 尝试过:

     <a xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xlink="http://www.w3.org/1999/xlink">      

<xsl:for-each select="child::*" >
<xsl:choose>

<xsl:when test="name()='track'">
<xsl:if test="@local">
<xsl:attribute name="xlink:href">

<xsl:value-of select="@local" />
</xsl:attribute>
</xsl:if>
<xsl:if test="@external">
<xsl:attribute name="xhtml:href">

<xsl:value-of select="@external" />
</xsl:attribute>
</xsl:if>
</xsl:when>
</xsl:choose>
</xsl:for-each>

</a>

但是当我根据条件为“a”元素创建属性时抛出异常。这在 XSLT 1.0 中不被接受,是否有任何方法可以根据 XSLT 1.0 中的某些条件为我的“a”元素显示属性。

最佳答案

这个转换:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xhtml="http://www.w3.org/1999/xhtml"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:my="my:my" exclude-result-prefixes="my">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>

<my:mappings>
<map from="external" to="xhtml"/>
<map from="local" to="xlink"/>
</my:mappings>

<xsl:variable name="vMaps" select="document('')/*/my:mappings/*"/>
<xsl:variable name="vNamespaces" select="document('')/*/namespace::*"/>

<xsl:template match="/*">
<t><xsl:apply-templates/></t>
</xsl:template>

<xsl:template match="track">
<xsl:element name="a"
namespace="{$vNamespaces[name()=$vMaps[@from=name(current()/@*)]/@to]}">
<xsl:apply-templates select="node()|@*"/>
</xsl:element>
</xsl:template>

<xsl:template match="@*">
<xsl:attribute name="{$vMaps[@from=name(current())]/@to}:href"
namespace="{$vNamespaces[name()=$vMaps[@from=name(current())]/@to]}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>

应用于此 XML 文档时:

<t>
<track external="http://mysite.com" />
<track local="/myfolder" />
</t>

产生想要的、正确的结果:

<t xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xlink="http://www.w3.org/1999/xlink">
<a xmlns="http://www.w3.org/1999/xhtml" xhtml:href="http://mysite.com"/>
<a xmlns="http://www.w3.org/1999/xlink" xlink:href="/myfolder"/>
</t>

请注意此解决方案具有一些独特的功能,例如:

  1. 没有使用条件指令,因此代码更简单,不易出错。

  2. 使用纯“推”的方式。

  3. 产生了完全想要的结果。

关于xslt - 如何根据 xslt 代码中的条件限制为标签添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11310939/

24 4 0