views:

45

answers:

2

Hey,

I have some xml, say:

<Background>
 <Uses>14</Uses>
</Background>
<Background>
 <Uses>19</Uses>
</Background>
<Background>
 <Uses>3</Uses>
</Background>

How can I sort the xml from lowest Uses to highest?

Maybe an xpath expression?

Also, how could I just retrieve the bottom 2 Backgrounds, or the ones most recently added?

Thanks

+1  A: 

Possible solution:

  • Parse the XML using SimpleXml
  • Use usort to sort the array containing the background elements.
  • Optionally, export it to XML again (there is no built-in function to do this)

Usort would work as follows:

function comp($a, $b) {
    return $b->Uses - $a->Uses;
}

usort($xml->Backgrounds, 'comp');

Another way is to use an XSLT, with something like this:

<xsl:sort select="Uses"/>
Sjoerd
How would I implement the XSLT?
apple
A: 

Example of sorting with XSLT

XML file:

<employees>

  <employee hireDate="04/23/1999">
    <last>Hill</last>
    <first>Phil</first>
    <salary>100000</salary>
  </employee>

  <employee hireDate="09/01/1998">
    <last>Herbert</last>
    <first>Johnny</first>
    <salary>95000</salary>
  </employee>

  <employee hireDate="08/20/2000">
    <last>Hill</last>
    <first>Graham</first>
    <salary>89000</salary>
  </employee>

</employees>

XSLF file:

<!-- xq424.xsl: converts xq423.xml into xq425.xml -->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     version="1.0">

  <xsl:output method="text"/>

  <xsl:template match="employees">
    <xsl:apply-templates>
      <xsl:sort select="salary"/>
    </xsl:apply-templates>
  </xsl:template>

  <xsl:template match="employee">
    Last:      <xsl:apply-templates select="last"/>
    First:     <xsl:apply-templates select="first"/>
    Salary:    <xsl:apply-templates select="salary"/>
    Hire Date: <xsl:apply-templates select="@hireDate"/>
    <xsl:text>
  </xsl:text>

  </xsl:template>

</xsl:stylesheet>

Source: http://www.xml.com/pub/a/2002/07/03/transform.html

Check predicates here: http://www.w3schools.com/XPath/xpath_syntax.asp for last three nodes.

MartyIX