jjohnson
jjohnson

Reputation: 203

How do I generate a comma-separated list with XSLT

Im trying to import a XML with a XSLT in ms access so that it imports with the list as comma separated
My XML:

<entry>
    <title>Adobe</title>
    <description>Adobe Acrobat</description>
    <title>Adobe1</title>
    <description>Adobe Acrobat1</description>
    <title>Adobe2</title>
    <description>Adobe Acrobat2</description>
</entry>

My attempt:

<xsl:for-each select="entry">
    <xsl:if test="position() > 1">, </xsl:if>
    <xsl:value-of select="title"/>
</xsl:for-each>

Expected results: Adobe, Adobe1, Adobe2

Upvotes: 2

Views: 1483

Answers (1)

Tim C
Tim C

Reputation: 70628

Your XML only has one entry, so the code within the xsl:for-each will only run once. And doing <xsl:value-of select="title" /> will only select the first title within that entry (Assuming XSLT 1.0, that is)

Change it to this...

<xsl:for-each select="entry/title">
    <xsl:if test="position() > 1">, </xsl:if>
    <xsl:value-of select="."/>
</xsl:for-each>

Note that in XSTL 2.0, you could replace the above code snippet entirely with this...

 <xsl:value-of select="entry/title" separator="," />

EDIT: Suppose your XSLT looks like this...

<iavmNotice xmlns="http://stuff.com" noticeId="138643">
   <title>Cisco Vulnerability</title>
   <techOverview>
      <entry>
         <title>2012-2490</title>
         <description>Cisco ID 71.</description>
      </entry>
      <entry>
         <title>2012-2525</title>
         <description>Cisco ID 69.</description>
      </entry>
   </techOverview>
</iavmNotice>

Then, to use xsl:for-each in context, you would add a template like so:

<xsl:template match="stuff:techOverview">
    <xsl:copy>
        <xsl:for-each select="stuff:entry/stuff:title">
            <xsl:if test="position() > 1">, </xsl:if>
            <xsl:value-of select="."/>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

Do note the following:

  • Ensure the stuff prefix is bound to the correct namespace as per the input XML
  • Ensure you have no other templates matching stuff:techOverview

Upvotes: 4

Related Questions