How to replace a node-name with another in Xslt?

后端 未结 3 659
渐次进展
渐次进展 2020-12-17 05:34

Bad wording on the question, sorry about that. Will try to explain what I\'m trying to do. Basically I have the output from a search as Xml and in that Xml there is a node l

相关标签:
3条回答
  • 2020-12-17 06:04

    This should do what you need. It uses the apply template instead of calling templates and is more of a functional way to tackle this problem.

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <!-- Template to match your 'key' and replace with strong -->
        <xsl:template match="FIELD[@name='body']/key">
            <strong><xsl:apply-templates select="@*|node()"/></strong>
        </xsl:template>
    
        <!-- Template to match all nodes, copy them and then apply templates to children. -->
        <xsl:template match="@*|node()">
          <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
          </xsl:copy>
        </xsl:template>
    </xsl:stylesheet>
    
    0 讨论(0)
  • 2020-12-17 06:08

    Why can't you just replace the "KEY" element with "STRONG" elements? Better not to think too imperatively about this.

    <xsl:template match="FIELD[@NAME='body']">
      <xsl:apply-templates/>
    <xsl:template>
    
    <xsl:template match="key">
      <strong>
      <xsl:apply-templates/>
      <strong>
    </xsl:template>
    
    <xsl:template match="text()">
      <xsl:copy-of select="."/>
    </xsl:template>
    

    Or did I misunderstand you?

    0 讨论(0)
  • 2020-12-17 06:15

    The best thing to do in such situations is to recursively copy nodes from input to output and override the nodes that you want to treat differently. The key idea is that the text strings are nodes which can be copied too. Here's an example:

    <xsl:template match="key">
        <strong>
            <xsl:apply-templates select="@*|node()"/>
        </strong>
    </xsl:template>
    
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    
    0 讨论(0)
提交回复
热议问题