Using xsl:element and xsl:attribute : xml output « XSLT stylesheet « XML Tutorial






File: Data.xml

<?xml version = "1.0"?>
<sports>
   <game title = "cricket">
      <id>243</id>
      <para>
         para 1
      </para>
   </game>
   <game title = "baseball">
      <id>431</id>
      <para>
         para 2
      </para>
   </game>
   <game title = "soccer">
      <id>123</id>
      <para>
         para 3
      </para>
   </game>

</sports>

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

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

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

  <xsl:template match="game">
    <xsl:element name="{@title}">
      <xsl:attribute name="id">
            <xsl:value-of select="id" />
         </xsl:attribute>
      <comment>
        <xsl:value-of select="para" />
      </comment>
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>

Output:

<?xml version="1.0" encoding="UTF-8"?><sports>
   <cricket id="243"><comment>
         para 1
      </comment></cricket>
   <baseball id="431"><comment>
         para 2
      </comment></baseball>
   <soccer id="123"><comment>
         para 3
      </comment></soccer>

</sports>








5.4.xml output
5.4.1.Convert xml structure
5.4.2.Output xml with namespace
5.4.3.Output xml tags
5.4.4.Add new tags to xml document
5.4.5.output xml element with namespace
5.4.6.Output element with default namespace
5.4.7.Add new tags to xml
5.4.8.Set cdata-section-elements
5.4.9.Restructure xml
5.4.10.Using xsl:element and xsl:attribute