Question

I have a template for a trailer record that has a parameter 'numberOfRecords' .

 <xsl:template name="render-FileTrailer">
    <xsl:param name="fileRecordIdentifier" select="TR"/>
    <xsl:param name="numberOfRecords"/>
  </xsl:template>

This number should the total count for my parent record and all of its children records. An example would be

<people>
  <person>
    <name> Mark</name>
    <age>32</age>
    <children>
      <child>
        <name> Mark Jr.</name>
        <age> 2</age>
      </child>
      <child>
        <name> Angel</name>
        <age> 4</age>
      </child>
    </children>
  </person>
</people>

so this would return 3, 1(mark) + 2(his two children)

How can I do this? This is my first time ever working with XSLT's.

Was it helpful?

Solution

You can obtain a count of all the people and child elements in your document with the following XPath:

count(//person|//child)

Applied to your template, it will create a default value for the numberOfRecords parameter:

<xsl:template name="render-FileTrailer">
    <xsl:param name="fileRecordIdentifier" select="TR"/>
    <xsl:param name="numberOfRecords" select="count(//person|//child)"/>
</xsl:template>

Or you can specify that value when calling the template, like this:

    <xsl:call-template name="render-FileTrailer">
        <xsl:with-param name="numberOfRecords" select="count(//person|//child)"/>
    </xsl:call-template>

OTHER TIPS

Since you say you're new to XSLT, there may be some things you're confused about :-) The intended use of the fileRecordIdentifier and numberOfRecords parameters is unclear. In any case, you can't use them to return values from the template; XSLT doesn't work that way. I'll answer the best I can given the question as it currently stands.

The stylesheet below will call your template, which adds the number of all people elements and all child elements. The result will simply be "3" (not valid XML, by the way). This could be equally well done in the root template, though, so it would be good to clarify the intended use of the render-FileTrailer template. If you elaborate on the question somewhat, we can take it further.

As a side note, your XML file is missing the / in some of the closing tags.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
   <xsl:template match="/">
      <xsl:call-template name="render-FileTrailer"/>
   </xsl:template>

   <xsl:template name="render-FileTrailer">
      <xsl:sequence select="count(//people) + count(//child)"/>
   </xsl:template>
</xsl:stylesheet>

Use this single XPath expression:

count(/*/person) + count(/*/person/children/child)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top