Search code examples
xpathxslt

Select one element, with preference for an order of id's


Taken the following example XML. I would like to select the elm in preference of the order of the following id sequence: 1, 3, 2.

<my:elmList>
    <elms>
        <elm>
            <id>3</id>
        </elm>
        <elm>
            <id>1</id>
        </elm>
        <elm>
            <id>2</id>
        </elm>
    </elms>
    <elms>
        <elm>
            <id>2</id>
        </elm>
        <elm>
            <id>3</id>
        </elm>
    </elms>
</my:elmList>

The resulting output should be 1 and 3, respectively to the elms element. Let me emphasize that I can't use [min(./id)] since I need 1 in preference of 2 and 3, but need 3 in preference of 2.


Solution

  • An XPath 2.0 solution that works for any set of IDs (not just single digits) would be

    (for $id in ("1", "3", "2") return elm[@id=$id])[1]