A. F.
A. F.

Reputation: 23

XSL Grouping by Sections

Using XSL 1.0, I am trying to get the data between two "Section" elements. I have no trouble getting just the "Heading" information alone, but I'd also like to know what Section that falls between since they are not siblings. That's where I get screwed up.

I have searched the web and this forum for various solutions, mostly trying to generate a key and using grouping, but I have been unsuccessful in getting anything that works. Sometimes it's a "whitespace expected" error or nothing at all.

INPUT:

<Root>
  <Content>
    <Paragraph Type="New Section">
      <Text>Section A</Text>
    </Paragraph>
    <Paragraph Type="Stuff">
      <Text>Random information 1</Text>
    </Paragraph>
    <Paragraph Type="Heading">
      <Text>Important information 1</Text>
    </Paragraph>
    <Paragraph Type="Stuff">
      <Text>Random information 2</Text>
    </Paragraph>
    <Paragraph Type="Heading">
      <Text>Important information 2</Text>
    </Paragraph>
    <Paragraph Type="End Of Section">
      <Text>End of Section A</Text>
    </Paragraph>
    <Paragraph Type="New Section">
      <Text>Section B</Text>
    </Paragraph>
    <Paragraph Type="Stuff">
      <Text>Random information 3</Text>
    </Paragraph>
    <Paragraph Type="Heading">
      <Text>Important information 3</Text>
    </Paragraph>
    <Paragraph Type="Stuff">
      <Text>Random information 4</Text>
    </Paragraph>
    <Paragraph Type="Heading">
      <Text>Important information 4</Text>
    </Paragraph>
    <Paragraph Type="End Of Section">
      <Text>End of Section B</Text>
    </Paragraph>
  </Content>
</Root>

DESIRED OUTPUT:

"Important information 1"
"Section A"
"Important information 2"
"Section A"
"Important information 3"
"Section B"
"Important information 4"
"Section B"

As I mentioned, using a choose and when test against Paragraph/@Type = "Heading" I am able to get the "Important information" text, but I cannot figure out how to tell between which Sections they fall.

Thank you in advance.

Upvotes: 1

Views: 50

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116992

I cannot figure out how to tell between which Sections they fall.

If you restate the problem as "which section was the last one to start prior to the current heading", then it becomes fairly trivial:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>

<xsl:template match="/Root">
    <xsl:for-each select="Content/Paragraph[@Type='Heading']">
        <xsl:value-of select="Text"/>
        <xsl:text>&#10;</xsl:text>
        <xsl:value-of select="preceding-sibling::Paragraph[@Type='New Section'][1]/Text"/>
        <xsl:text>&#10;</xsl:text>      
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Upvotes: 2

Related Questions