Can anyone show me how to sort an XML file containing numeric data as well as string data stored in separate tags? For example I have a Charges (numeric) and Network (string) elements. Now I want to sort the XML file on the basis of Charges in Javascript.
any simple examples?
<Results>
<network>Wateen</network>
<speed>2048</speed>
<type>Fixed</type>
<install_charges>500</install_charges>
<charge开发者_高级运维s>20</charges>
</Results>
<Results>
<network>PTCL</network>
<speed>4096</speed>
<type>Fixed</type>
<install_charges>0</install_charges>
<charges>2000</charges>
</Results>
<Results>
<network>PTCL</network>
<speed>4096</speed>
<type>Fixed</type>
<install_charges>0</install_charges>
<charges>200</charges>
</Results>
<Results>
<network>PTCL</network>
<speed>4096</speed>
<type>Fixed</type>
<install_charges>0</install_charges>
<charges>3000</charges>
</Results>
How do I sort the above XML according to the charges
? It will also be nice if it is non-XSL method because XSL give lots of trouble.
If you don't like to use XSL you can make an array containing the Results-elements and use the native sort-method of arrays:
<Results>
<network>Wateen</network>
<speed>2048</speed>
<type>Fixed</type>
<install_charges>500</install_charges>
<charges>20</charges>
</Results>
<Results>
<network>PTCL</network>
<speed>4096</speed>
<type>Fixed</type>
<install_charges>0</install_charges>
<charges>2000</charges>
</Results>
<Results>
<network>PTCL</network>
<speed>4096</speed>
<type>Fixed</type>
<install_charges>0</install_charges>
<charges>200</charges>
</Results>
<Results>
<network>PTCL</network>
<speed>4096</speed>
<type>Fixed</type>
<install_charges>0</install_charges>
<charges>3000</charges>
</Results>
<script>
var nodeArray=[];
var nodeList=document.getElementsByTagName('Results')
//fill array
for(var i=0;i<nodeList.length;++i)
{
nodeArray.push(nodeList[i]);
}
//sort array
nodeArray.sort(function(a,b)
{
return (
Number(a.getElementsByTagName('charges')[0].firstChild.data)
-
Number(b.getElementsByTagName('charges')[0].firstChild.data)
);
});
//reorder nodes
for(var i=nodeArray.length-1;i>=0;i--)
{
nodeArray[i]
.parentNode
.insertBefore(nodeArray[i],
nodeArray[i].parentNode.getElementsByTagName('Results')[0]);
}
</script>
精彩评论