1

I have an xml with several large sections of similar data. I want to be able to select one section based on a priority list and whether or notthe section exists.

For example If section A exist only use A if it does not exist use B and so on but only use the first section that it finds, based on a priority I set not the order in the xml.

Here is the xsl so far:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:template match="/">
        <xsl:apply-templates select="sources/source"></xsl:apply-templates>
    </xsl:template>

     <xsl:template match="source">
    <xsl:choose>
                <xsl:when test="@type='C' or @type='B' or @type='A'">
                <xsl:value-of select="name"/>
                <xsl:value-of select="age"/>
            </xsl:when>
        </xsl:choose>

    </xsl:template>


</xsl:stylesheet>

Here is the xml exmple:

<?xml version="1.0" encoding="UTF-8"?>
<sources>
    <source type='C'>
        <name>Joe</name>
        <age>10</age>
    </source>
    <source type='B'>
        <name>Mark</name>
        <age>20</age>
    </source>
    <source type='A'>
        <name>David</name>
        <age>30</age>
    </source>
</sources>

So what I am tying to say here is C is my first choice, then B then A.

Mathias Müller
  • 22,203
  • 13
  • 58
  • 75
Alex
  • 1,891
  • 3
  • 23
  • 39

1 Answers1

2

Just select a sequence in the order of preference and then use the first item in the sequence...

XSLT 2.0

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/">
        <xsl:apply-templates select="(sources/source[@type='C'],
                                      sources/source[@type='B'],
                                      sources/source[@type='A'])[1]"/>
    </xsl:template>

    <xsl:template match="source">
        <xsl:value-of select="name,age" separator=" - "/>
    </xsl:template>

</xsl:stylesheet>

Output

Joe - 10

Note: I changed the override of source for demonstration purposes only.

Daniel Haley
  • 51,389
  • 6
  • 69
  • 95