tags:

views:

30

answers:

2

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</lastname>
    <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.

A: 

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>
AJPerez
AJPerez, thank you. It did put double quotes around all values with text. I also need double quotes for empty strings, what can I add to get <Address2>""</Address2> instead of <Address2/>?
Walinmichi
+1  A: 

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
 <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>
Dimitre Novatchev