L.krez
L.krez

Reputation: 41

Adding newline between elements in XSLT

I'm beggining in XML and XSLT and I have a problem with adding a new line beetwen elements

Here's XML:

<?xml version="1.0" encoding="UTF-8"?>
<numbers>
    <person id="1">
        <phone>
         <phone_nr>111111111</phone_nr>
         <phone_nr>222222222</phone_nr>
        </phone>
    </person>
    <person id="2">
        <phone>
          <phone_nr>333333333</phone_nr>
            </phone>
    </person>
</numbers>

XSLT looks like:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <xsl:for-each select="numbers/person">
    <table border="1">
      <tr>
       <td>
       <table>
         <td><xsl:value-of select="phone"/></td>
       </table>
      </td>
     </tr>
    </table>
    </xsl:for-each>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

and it gives me this (with borders) :

111111111 222222222
333333333

but what I want is:

111111111
222222222
333333333

The problem is that XML must be like this and I don't know, how to creating a new line in XSLT.

Upvotes: 2

Views: 2630

Answers (2)

michael.hor257k
michael.hor257k

Reputation: 117100

It's difficult to answer your question without knowing what the exact output should be. Going just by what you showed us, the simplest way would be:

<xsl:template match="/numbers">
    <table border="1">
        <xsl:for-each select="person/phone/phone_nr">
            <tr>
                <td><xsl:value-of select="."/></td>
            </tr>
        </xsl:for-each>
    </table>
</xsl:template>

Upvotes: 0

Tim C
Tim C

Reputation: 70648

You are outputting HTML, so to do a "newline" you need to output a <br> tag. The problem you have at the moment is that you are outputting the text value of the phone element, which concatenates all the text nodes under it together. You really need to handle the child phone_nr nodes separately, with an xsl:for-each for example

   <td>
       <xsl:for-each select="phone/phone_nr">
          <xsl:value-of select="."/><br />
       </xsl:for-each>
    </td>

Try this XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
    <xsl:for-each select="numbers/person">
    <table border="1">
      <tr>
       <td>
           <xsl:for-each select="phone/phone_nr">
              <xsl:value-of select="."/><br />
           </xsl:for-each>
        </td>
     </tr>
    </table>
    </xsl:for-each>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

Upvotes: 3

Related Questions