tara
tara

Reputation: 77

How to get text nodes in order using xsl?

I'd like to get text nodes and element nodes under 'fomula' element in order, to transform XML into HTML. I show the XML code below. Texts are not fixed. (I wrote the code in more detail again.)

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <section>
        <formula>
            m=12n
            <superscript>
                2
            </superscript>
            +3(3n
            <superscript>
                2
            </superscript>
            +2)
        </formula>
        <xxx>
            abc
        </xxx>
        <formula>
            c=a+b
            <superscript>
                4
            </superscript>
        </formula>
    </section>
</root>

What should I write XSL to get the result below?

<p>m=12n<span>2</span>+3(3n<span>2</span>+2</p>
<p>abc</p>
<p>c=a+b<span>4</span></p>

I usually write XSL like below when I get specific element nodes. But I don't know how to get text nodes with sibling element nodes in order. Please give me advices. (I wrote the code in more detail again.)

<xsl:template match="/">
    <html>
        --omitted--
        <body>
            <xsl:apply-templates select="/root/section" />
        </body>
    <html>
</xsl:template>
<xsl:template match="section">
    <xsl:for-each select="*">
        <xsl:if test="name()='formula'">
            <xsl:apply-templates select="." />
        </xsl:if>
        <xsl:if test="name()='xxx'">
            <xsl:apply-templates select="." />
        </xsl:if>
    </xsl:for-each>
</xsl:template>
<xsl:template match="formula">
    <p>
        <xsl:apply-templates select="." />
    </p>
</xsl:template>
<xsl:template match="xxx">
    <p>
        <xsl:apply-templates select="." />
    </p>
</xsl:template>

Upvotes: 1

Views: 185

Answers (1)

Rubens Farias
Rubens Farias

Reputation: 57996

You should take a look into xsl:template and xsl:apply-templates:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

   <xsl:template match="/">
      <xsl:apply-templates select="/root/section"/>
   </xsl:template>

   <xsl:template match="formula | xxx">
      <p>
         <xsl:apply-templates />
      </p>
   </xsl:template>

   <xsl:template match="superscript">
      <span>
         <xsl:apply-templates />
      </span>
   </xsl:template>

</xsl:stylesheet>

You can see a working example here.

EDIT: a possible approach is to create a template for every specific format you need. So:

  • "every time I find a formula or a xxx element, I shall enclose it's content in a p element"
  • "every time I find a superscript element, I shall enclose it's content in a span element"

Upvotes: 3

Related Questions