tags:

views:

51

answers:

3

I want to add some strings in the text right after a leading space. Any ideas how to detect the leading space? Thanks.

For example, I would like to add "def" in front of abc but after the leading space.

<AAA>
    <CCC> abc</CCC>
</AAA>

Output should become: " defabc"

+1  A: 

Assuming, from your tag, that you are trying to do this in xslt, I'd use XSLT's starts-with function.

If you provide some example XSLT code, it'd be easier to explain more.

JesseW
Yes, I am trying to use XSLT 1.0 to do some XML processing. What I want to do is to check if first character is a space. If it is, then I need to insert a custom string after the space.
Wilson
I suppose I should use the "starts-with" function and then the "insert-at" function to do what I want to do. Right?
Wilson
er, there is no insert-at function, AFAIK. But once you get the text node, just use substring-after to strip off the leading space, then concat to do the insertion.
JesseW
OK. Thanks. Let me try.
Wilson
+2  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:strip-space elements="*"/>

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

 <xsl:template match="text()[starts-with(.,' ')]">
   <xsl:value-of select=
   "concat(' ', 'def', substring(.,2))"/>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<AAA>
    <CCC> abc</CCC>
</AAA>

produces the wanted, correct result:

<AAA>
   <CCC> defabc</CCC>
</AAA>
Dimitre Novatchev
@Dimitre: +1 Good answer
Alejandro
A: 

Besides Dimitre's answer with proper use of pattern matching, this XPath expression could help you:

concat(substring($AddString, 1 div starts-with($String,' ')), $String)
Alejandro