XPath 1.0 Attribute Return Order in UNION

<merge>
    <text>
        <div begin="A"   end="B" />
        <div begin="C"   end="D" />
        <div begin="E"   end="F" />
        <div begin="G"   end="H" />
    </text>
</merge>

I need a UNIONed set of attribute nodes in order A, B, C, D, E, F, G, H, and this will work:

/merge/text/div/@begin | /merge/text/div/@end

but only if every @begin comes before every @end, since the UNION operator must return the nodes in document order. (Yes?)

I need a set of nodes in the same order, even if the attributes are displayed in a different order in the document, as here:

<merge>
    <text>
        <div end="B"   begin="A" />
        <div begin="C" end="D"   />
        <div end="F"   begin="E" />
        <div begin="G" end="H"   />
    </text>
</merge>

That is, I need elements to follow the order of the document, but the attributes in each element must follow a specific order (specified or alphabetically by attribute name).

+5
source share
1 answer

This is simply not possible in pure XPath. First of all, attributes in XML are unordered. From XML Recommendation 1.0 :

, - empty-element .

XPath , , , .

-, XPath . , - (, XSLT PL ) .

, XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    <xsl:template match="/">
        <xsl:apply-templates
            select="/merge/text/div/@*[name()='begin' or name()='end']">
            <xsl:sort select="."/>
        </xsl:apply-templates>
    </xsl:template>
</xsl:stylesheet>

, .

: / ( ):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="div">
        <xsl:value-of select="concat(@begin, @end)"/>
    </xsl:template>
</xsl:stylesheet>
+6

All Articles