如何使用xslt 1.0替换第一个<p>标签</p> <p property =“v:street-address”> </p>

时间:2013-02-10 11:18:40

标签: xml xslt xslt-1.0 msxsl

这条xsl:apply-templates指令:

<xsl:if test="$item/tcm:Content/em:Office/em:Address">
    <address>
        <xsl:apply-templates mode="renderhtml" select="$item/tcm:Content/em:Office/em:Address/node()" />
    </address>
</xsl:if>

产生

<p>
    My Office Address
    <br />XXXX Road
    <br />XXXX District
    <br />XXXX, XXXX.
    <br />PO Box XXXX
</p>

现在我想将生成的html存储在一个变量中,然后调用另一个模板将第一个<p>元素替换为<p property="v:street-address">,这样最终的结果就是:

<p property="v:street-address">
    My Office Address
    <br />XXXX Road
    <br />XXXX District
    <br />XXXX, XXXX.
    <br />PO Box XXXX
</p>

请建议!!

由于

2 个答案:

答案 0 :(得分:1)

在XSLT 1.0中,如果您使用的是支持the node-set() function的处理器,则只能捕获输出并将模板应用于该输出。假设你是,你可以这样做:

<xsl:if test="$item/tcm:Content/em:Office/em:Address">
    <address>
      <xsl:variable name="addressHtml">
        <xsl:apply-templates mode="renderhtml" 
                             select="$item/tcm:Content/em:Office/em:Address/node()" />
      </xsl:variable>
      <xsl:apply-templates select="msxsl:node-set($addressHtml)" 
                           mode="adjustAddressHtml" />
    </address>
</xsl:if>

...

  <xsl:template match="@* | node()" mode="adjustAddressHtml" name="Identity">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()" mode="adjustAddressHtml" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="/" mode="adjustAddressHtml">
    <xsl:if test="p">
      <xsl:call-template name="Identity" />
    </xsl:if>
    <xsl:if test="not(p)">
      <xsl:call-template name="StartingP" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="/p[1]" mode="adjustAddressHtml" name="StartingP">
    <p property="v:street-address">
      <xsl:apply-templates select="@* | node()" mode="adjustAddressHtml" />
    </p>
  </xsl:template>

答案 1 :(得分:0)

如果没有提供源XML文档,很难给出完整的答案,但通常可以避免需要进行两遍转换

相反,XSLT代码可以像那样简单:

某处:

<xsl:apply-templates mode="renderhtml"
         select="$item/tcm:Content/em:Office/em:Address/>

然后:

 <xsl:template match="em:Address" mode="renderhtml">
  <address>
      <xsl:apply-templates mode="renderhtml" select="node()" />
  </address>
 </xsl:template>

 <xsl:template match="em:Address/node()" mode="renderhtml">
    <p>
     <xsl:if test="position() = 1">
      <xsl:attribute name="property">v:street-address</xsl:attribute>
     </xsl:if>
       <!-- The code that generates this:
        My Office Address
        <br />XXXX Road
        <br />XXXX District
        <br />XXXX, XXXX.
        <br />PO Box XXXX
         -->
    </p>
 </xsl:template>