Home > other >  xslt 2.0 replace with xml-structure
xslt 2.0 replace with xml-structure

Time:09-16

I am using xslt 2.0 and the replace-function. My task is to replace a part of a string with structure. Example

Input:

<xml>
<content>Title 1: This will be on a new line</content>
</xml>

Output:

<xml>
<content>Title 1:</content><content>This will be on a new line</content>
</xml>

According to xslt 2.0 I am not allowed to have < or > in the replace string. And if I use < or > that is being output as well...

xslt I am using is sort of like this:

<xsl:value-of select="replace(., '(.*)\s (.*)', $1</content><content>$2"/>

CodePudding user response:

AFAICT, you want to do simply:

<xsl:template match="content">
    <xsl:analyze-string select="." regex="^\D*\d :\s ">
        <xsl:matching-substring>
            <content>
                <xsl:value-of select="normalize-space(.)"/>
            </content>
        </xsl:matching-substring>
        <xsl:non-matching-substring>
            <content>
                <xsl:value-of select="."/>
            </content>
        </xsl:non-matching-substring>
    </xsl:analyze-string>
</xsl:template>

Demo: https://xsltfiddle.liberty-development.net/nbiE1b5/1

CodePudding user response:

Thanks to comment from michael-hor257k I was able to solve this problem. I had to do some tweaks, but it did work.

Here is the solution:

<xsl:analyze-string select="." regex="(.*)(\d )\s (.*)">
            <xsl:matching-substring>
                <xsl:value-of select="regex-group(1)"/>
                <xsl:text> </xsl:text>
                <xsl:value-of select="regex-group(2)"/>
                <xsl:call-template name="ELEMENT_CONTENT_END"/>
                <xsl:call-template name="ELEMENT_BR"/>
                <xsl:call-template name="ELEMENT_CONTENT_START"/>
                    <xsl:value-of select="regex-group(3)"/>
            </xsl:matching-substring>
            <xsl:non-matching-substring>
                <xsl:value-of select="normalize-space(.)"/>
            </xsl:non-matching-substring>
        </xsl:analyze-string>

ELEMENT_CONTENT_START and ELEMENT_CONTENT_START is defined as following:

<xsl:template name="ELEMENT_CONTENT_END">
        <xsl:text disable-output-escaping="yes">&lt;/content&gt;&#10;</xsl:text>
    </xsl:template>

<xsl:template name="ELEMENT_CONTENT_START">
        <xsl:text disable-output-escaping="yes">&lt;content&gt;&#10;</xsl:text>
    </xsl:template>

Thanks for the valuable suggestion, Michael!

  • Related