I was facing a problem to sort xml response based on more than one field.
Tried to use Transform Sort Builder but unable to implement it.
Finally implemented a solution of writing my custom comparator to sort the XML response.
My Sample XML Response :
<?xml version="1.0"
encoding="utf-8"?>
<Invoices>
<Invoice>
<Date>06/10/2013 16:14:26</Date>
<InvoiceId>str1234</InvoiceId>
<Client>str1234</Client>
<BillingEntity>str1234</BillingEntity>
<UserAccess>str1234</UserAccess>
<Reports>
<Report>str1234</Report>
</Reports>
</Invoice>
</Invoices>
// Sort Method
public IXml sort(WebAppAccess
webAppAccess, IXml sourceData) {
System.out.println("!!!!!!In
SortInvioceReportLJO.sort 111111111!!!!!!!!!!!!!!");
IXml result =
sourceData.cloneElement();
IXml parent = result;
// find the elements to be sorted
List elements = XmlUtil.findElements(parent,
"Invoices/Invoice");
// loop through each element to be sorted
Iterator iterator =
elements.iterator();
while (iterator.hasNext()) {
IXml element = (IXml)iterator.next();
// remove the element from its parent
element
parent.removeChildElement(element);
}
// sort the list of elements
System.out.println("!!!!!!In
SortInvioceReportLJO.Collection Sort!!!!!!!!!!!!!!");
Collections.sort(elements, new CustomComparator());
// loop through each element again - in the
sorted order now
iterator = elements.iterator();
while (iterator.hasNext()) {
IXml element = (IXml)iterator.next();
// add the element back to its parent
element
parent.addChildElement(element);
}
System.out.println("!!!!!!Returning
from SortInvioceReportLJO.sort== "+result);
return result;
}
// Custom Comparator Class
public class CustomComparator implements Comparator {
public int compare(Object o1,
Object o2) {
System.out.println("In
CustomComparator compare !! ");
IXml e1;
IXml e2;
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
int i = 0;
try{
if((o1 instanceof IXml)
&& (o2 instanceof IXml)){
e1 = (IXml)o1;
e2 = (IXml)o2;
System.out.println("In Comparator
o1!!! "+o1);
System.out.println("In Comparator
o2!!! "+o2);
i =
sdf.parse(e2.getText("Invoice/Date")).compareTo(sdf.parse(e1.getText("Invoice/Date")));
if(i==0){
i = (Integer.valueOf((e1.getText("Invoice/InvoiceId")))).compareTo(Integer.valueOf((e2.getText("Invoice/InvoiceId"))));
}
System.out.println("In Comparator
i === "+i);
}
}catch(ParseException ex){
System.out.println("CustomComparator
Exception in Parsing !! "+ex);
}
return i;
}
}
Hope it'll be helpful.
No comments:
Post a Comment