Resource: stocks.xml and stocks.xsl (XSLT Example)

 

The XSLT example uses stocks.xml and stocks.xsl as resource files.

To add stocks.xml and stocks.xsl to the project

  1. Create a new C++ source file. For detailed instructions on how to do this, see Set Up My Visual C++ Project. Name the new file stocks.xml

  2. Copy stocks.xml, above, and paste it into the source file you just created.

  3. Create another new C++ source file.

  4. Copy the XSD file above and paste it into the source file you just created.

    Note

    You can also copy the files into the project's main directory using Windows Explorer (or a command prompt).

  5. Next, build and run the XSLT project. The result should be the output shown in the following topic.

XML File (stocks.xml)

<?xml version="1.0"?>
<?xml:stylesheet type="text/xsl" href="stock.xsl"?>
<portfolio xmlns:dt="urn:schemas-microsoft-com:datatypes">
  <stock exchange="nasdaq">
    <name>new</name>
    <symbol>zzzz</symbol>
    <price dt:dt="number">20.313</price>
  </stock>
  <stock exchange="nyse">
    <name>zacx corp</name>
    <symbol>ZCXM</symbol>
    <price dt:dt="number">28.875</price>
  </stock>
  <stock exchange="nasdaq">
    <name>zaffymat inc</name>
    <symbol>ZFFX</symbol>
    <price dt:dt="number">92.250</price>
  </stock>
  <stock exchange="nasdaq">
    <name>zysmergy inc</name>
    <symbol>ZYSZ</symbol>
    <price dt:dt="number">20.313</price>
  </stock>
</portfolio>

XSLT Style Sheet (stocks.xsl)

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
                version="1.0">
<xsl:template match="/">
<HTML>
  <BODY>
    <TABLE BORDER="2">
      <TR>
        <TD>Symbol</TD>
        <TD>Name</TD>
        <TD>Price</TD>
      </TR>
      <!-- Use xsl:apply-templates. -->
      <xsl:apply-templates select="portfolio/stock">
      <!-- Sort by stock symbols. -->
        <xsl:sort select="symbol"/>
      </xsl:apply-templates>      
    </TABLE>

  </BODY>
</HTML>
</xsl:template>

<xsl:template match="portfolio/stock">
      <TR>
   <!-- Use xsl:choose and xsl:when. -->
   <xsl:attribute name="STYLE">color:
     <xsl:choose>
            <xsl:when test="price[. &lt; 30]">green</xsl:when>
            <xsl:when test="price[. &gt; 50]">red</xsl:when>
     </xsl:choose>
   </xsl:attribute>

   <!-- Generate an attribute as a tooltip of TR. -->
   <xsl:attribute name="Title"><xsl:value-of select="symbol"/> is listed on the <xsl:value-of select="@exchange"/> stock exchange.</xsl:attribute>
        <TD><xsl:value-of select="symbol"/>
   <!-- Use xsl:if. -->
    <xsl:if test="@exchange[.='nasdaq']">*</xsl:if></TD>              
        <TD><xsl:value-of select="name"/></TD>
        <TD><xsl:value-of select="price"/></TD>
      </TR>
      </xsl:template>
</xsl:stylesheet>