Search code examples
xmlcsvxsltxslt-2.0

Need to take the label attribute into the title


I'm having the xml be like:

<sect1 label="Chapter 1:">
   <title>Pass</title>
   <sect2 label="1.1">
      <title>Pass 1</title>
      <sect3 label="1.1.1">
         <title>Pass 2</title>
         <sect4 label="1.1.1.1">
            <title>Pass 3</title>
         </sect4>
      </sect3>
    </sect2>
</sect1>

XSL Tried like:

<xsl:template match="/">
    <xsl:text>Heading,,,,,Sub Heading</xsl:text>
        <xsl:for-each select="//title[starts-with(name(..), 'sect')] ">
        <xsl:value-of select="for $i in 1 to count(ancestor::*) - 1 return ','" separator=""/>
        <xsl:value-of select="."/>
            <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
</xsl:template>

Getting output is:

Heading,,,,,Sub Heading
Pass
,Pass 1
,,Pass 2
,,,Pass 3

Expected output would be:

Heading,,,,,Sub Heading
Chapter 1: Pass
,1.1 Pass 1
,,1.1.1 Pass 2
,,,1.1.1.1 Pass 3

I need the label attribute comes before the title.


Solution

  • I think all you need to do is change this...

    <xsl:value-of select="."/>
    

    to this, to include the parent's label attribute

    <xsl:value-of select="../@label, ."/>
    

    Try this block (where I have simplified the xsl:for-each ever so slightly to, and added a line feed after the header row

    <xsl:template match="/">
        <xsl:text>Heading,,,,,Sub Heading&#10;</xsl:text>
        <xsl:for-each select="//*[starts-with(name(), 'sect')]/title">
            <xsl:value-of select="for $i in 1 to count(ancestor::*) - 1 return ','" separator=""/>
            <xsl:value-of select="../@label, ."/>
            <xsl:text>&#10;</xsl:text>
        </xsl:for-each>
    </xsl:template>