简体   繁体   中英

XSLT: mixed text and node - how to replace <b>

I searched and found this post from about 4 yrs ago: xsl - tag position with text mixed in parent and I am trying to do something simlar, but a little different... but cannot get it to work. How do I change:

<tag1>some <tag2>other</tag2> text</tag1>
into:
<tag1>some <bold>other</bold> text</tag1>

?

In other words, I have mixed text and nodes, and I want to rename the tag of a node, but keep the correct location within the text.

You haven't provided us any existing XSLT to start with so it's hard to tell you exactly how to fit this into what you have, but basically you need to be correctly using apply-templates and matching the elements that you need to swap out:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <!-- itentity template -->
  <xsl:template match="@* | node()">
    <xsl:copy>
      <!-- apply templates to contents -->
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="tag2">
    <bold>
      <xsl:apply-templates />
    </bold>
  </xsl:template>

</xsl:stylesheet>

When this is applied to your sample input:

<tag1>some <tag2>other</tag2> text</tag1>

The result is:

<tag1>some <bold>other</bold> text</tag1>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM