John Fraser
John Fraser

Reputation: 11

XSLT Sort parent node based on specific attribute of a child

first post ever, have done lots of searching but cannot find an answer specific enough or more importantly, relevant enough. Note that I am a business analyst, not a developer, so I may be missing some understanding here.

We produce XML that we then process to produce a report. Where data can be represented by a table, the XML contains details for the table title (ELEMENT_HEADING), table header row (PROMPTS), then repeating nodes representing the rows (DATA) and columns (VALUES).

The problem I am facing is I need to sort the DATA node based on a text value of the node where the node has a specific attribute value.

In the sample XML provided below, I need to sort the DATA node based on the VALUE text value for the attribute @pic='TRORGPCNT' in ascending order i.e the DATA node with TRORGPCNT of 10 should appear before the DATA node with 90. Then when the report is produced the table rows are in ascending percentage order.

I hope have explained myself clearly enough :)

Any tips on how I might accomplish this?

Sample XML:

<PROPOSAL_ELEMENT multi="Y" pec="TEACHRESP" elem_mandatory="N" elem_visible="Y">
        <ELEMENT_HEADING pec="TEACHRESP">Teaching Responsibility</ELEMENT_HEADING>
        <PROMPTS>
            <PROMPT pic="TRORGUN" item_mandatory="Y" item_visible="Y">Faculty or School with teaching responsibility</PROMPT>
            <PROMPT pic="TRORGPCNT" item_mandatory="Y" item_visible="Y">Teaching responsibility %</PROMPT>
        </PROMPTS>
        <DATA elem_mandatory="N" elem_visible="Y" delete_ind="N">
            <VALUES>
                <VALUE pic="TRORGUN" item_mandatory="Y" item_visible="Y" item_description="FACULTY OF NURSING AND HEALTH" display_in_summary_tab="Y" summary_order="">FACULTY OF NURSING AND HEALTH</VALUE>
                <VALUE pic="TRORGPCNT" item_mandatory="Y" item_visible="Y" item_description="" display_in_summary_tab="Y" summary_order="">90</VALUE>
            </VALUES>
        </DATA>
        <DATA elem_mandatory="N" elem_visible="Y" delete_ind="N">
            <VALUES>
                <VALUE pic="TRORGUN" item_mandatory="Y" item_visible="Y" item_description="FACULTY OF ARTS" display_in_summary_tab="Y" summary_order="">FACULTY OF ARTS</VALUE>
                <VALUE pic="TRORGPCNT" item_mandatory="Y" item_visible="Y" item_description="" display_in_summary_tab="Y" summary_order="">10</VALUE>
            </VALUES>
        </DATA>

Upvotes: 1

Views: 335

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122364

Sorting in XSLT is accomplished using the xsl:sort instruction, which must appear as the first child of the for-each or apply-templates that selects the nodes you want to sort. If you're selecting the set of DATA element nodes then an appropriate sorting instruction would be

<xsl:sort select="VALUES/VALUE[@pic='TRORGPCNT']"
  data-type="number" />

Upvotes: 2

Related Questions