Reputation: 1020
I have a xml like follows,
<session>
<p> This is first sentence</p>
<p> This is second sentance</p>
<session>
what I need is inset new node named <s>
to every space in <p>
content. number of consecutive space should be show as attribute of <s>
node.
I've written following xsl to do this,
<xsl:template match="p/text()" priority="10">
<xsl:analyze-string select="." regex=" ">
<xsl:matching-substring>
<xsl:if test="position() gt 0">
<tps:s c="{position()}"/>
</xsl:if>
<xsl:value-of select="."/>
</xsl:matching-substring>
<xsl:non-matching-substring>
<xsl:value-of select="."/>
</xsl:non-matching-substring>
</xsl:analyze-string>
</xsl:template>
the result of this code is follows,
<session>
<p><s c="1"/> This<s c="3"/> is<s c="5"/> first<s c="7"/> sentence</p>
<p><s c="1"/> <s c="2"/> <s c="3"/> <s c="4"/> <s c="5"/> <s c="6"/> <s c="7"/> <s c="8"/> <s c="9"/> <s c="10"/> This<s c="12"/> is<s c="14"/> second<s c="16"/> sentance</p>
</session>
As it shown above it adds <s>
for every space and but what I'm expecting is follows,
<session>
<p><s c="1"/>This<s c="1"/> is<s c="1"/> first<s c="1"/> sentence</p>
<p><s c="10"/> This<s c="1"/> is<s c="1"/> second<s c="1"/> sentance</p>
</session>
I tried to use variable but it did not succeed since variables are not varying in xslt. Can anyone suggest me a method to arrange my code to get expected output.
Thanks in adnanced
Upvotes: 0
Views: 32
Reputation: 167401
I would simply match on a sequence of blanks and count them:
<xsl:analyze-string select="." regex=" +">
<xsl:matching-substring>
<tps:s c="{string-length()}"/>
<xsl:text> </xsl:text>
</xsl:matching-substring>
The rest of your code remains unchanged.
Upvotes: 1