문제

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.

도움이 되었습니까?

해결책

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>

다른 팁

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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top