0

I already asked a question related to this, but I did not think I would face another problem. Here is my sample XML file :

<section>
    Hello everyone, I'm
    <bold>Hackmania</bold>
    <bold>15</bold>
    <line/>
    I am looking for an
    <highlight>answer</highlight>
    <paragraph/>

    Here is an other
    <bold>paragraph</bold>
    <highlight>with the same tags</highlight>
    <paragraph/>
</section>

How could I put my isolated texts into a specific tag, let's say <myText></myText>? like this :

<section>
    <p>
        <myText>Hello everyone, I'm</myText>
        <bold>Hackmania</bold>
        <bold>15</bold>
        <line/>
        <myText>I am looking for an</myText>
        <highlight>answer</highlight>
    </p>
    <p>
        <myText>HHere is an other</myText>
        <bold>paragraph</bold>
        <highlight>with the same tags</highlight>
    </p>
</section>

Thanks in advance for your help.

1 Answer 1

1

Instead of the

    <xsl:for-each select="paragraph">
        <p>
            <xsl:copy-of select="key('grpById', generate-id())"/>
        </p>
    </xsl:for-each>

in the referenced solution you can use

    <xsl:for-each select="paragraph">
        <p>
            <xsl:apply-templates select="key('grpById', generate-id())"/>
        </p>
    </xsl:for-each>

and then make sure you do

<xsl:template match="section/text()">
  <myText>
    <xsl:value-of select="normalize-space()"/>
  </myText>
</xsl:template>

plus the identity transformation template

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

to copy the rest unchanged.

So the whole stylesheet then is

<xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:key name="grpById" match="node()[not(self::paragraph)]" use="generate-id(following-sibling::paragraph[1])" />

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

    <xsl:template match="section/text()">
        <myText>
            <xsl:value-of select="normalize-space()"/>
        </myText>
    </xsl:template>

    <xsl:template match="/section">
        <xsl:copy>
            <xsl:for-each select="paragraph">
                <p>
                    <xsl:apply-templates select="key('grpById', generate-id())"/>
                </p>
            </xsl:for-each>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.