开发者

XSLT Replace Element Text with Enclosed Text Value

What XSLT is required to replace the text of a node with the same text enclosed in double quotes:

<users>
  <user_info>
    <lastname>Jenkins</lastname>
    <firstname>Bob</firstname>
  </user_info>
  <user_info>
    <lastname>Smith</lastna开发者_如何学运维me>
    <firstname>Mike</firstname>
  </user_info>
</users>

This is a simplified view, my user_info structure has 22 elements, so I would like the XSLT to simply replace the text of any child element text value with the same text enclosed in double quotes:

<users>
  <user_info>
    <lastname>"Jenkins"</lastname>
    <firstname>"Bob"</firstname>
  </user_info>
  <user_info>
    <lastname>"Smith"</lastname>
    <firstname>"Mike"</firstname>
  </user_info>
</users>

I can do the logic on a per child-element basis, but that is tedious. I'm confused on how to have the iteration occur at the user_info node-list level. As usual, the answer is probably very simple :) Thanks for the help.


This transformation:

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

 <xsl:variable name="vQ">"</xsl:variable>

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

 <xsl:template match="user_info/*/text()">
   <xsl:value-of select="concat($vQ, ., $vQ)"/>
 </xsl:template>

 <xsl:template match="user_info/*[not(node())]">
  <xsl:copy>
    <xsl:copy-of select="@*"/>
    <xsl:value-of select="concat($vQ, $vQ)"/>
  </xsl:copy>
 </xsl:template>
</xsl:stylesheet>

when applied on this XML document:

<users>
  <user_info>
    <lastname>Jenkins</lastname>
    <firstname>Bob</firstname>
    <address2></address2>
  </user_info>
  <user_info>
    <lastname>Smith</lastname>
    <firstname>Mike</firstname>
  </user_info>
</users>

produces the wanted result:

<users>
  <user_info>
    <lastname>"Jenkins"</lastname>
    <firstname>"Bob"</firstname>
    <address2>""</address2>
  </user_info>
  <user_info>
    <lastname>"Smith"</lastname>
    <firstname>"Mike"</firstname>
  </user_info>
</users>


I'm not 100% sure of the user_info//text() selector, but I think this would work:

<xsl:template match="user_info//text()">
  <xsl:text>"</xsl:text>
  <xsl:value-of select="."/>
  <xsl:text>"</xsl:text>
</xsl:template>

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜