0

I am trying to sort the nodes in a NodeList based on the Item ID. The Xml looks like

<Order>
 <Lines>
  <Line LineNo="1">
   <Item ID="ItemA1"/>
  </Line>
  <Line LineNo="2">
   <Item ID="ItemA4"/>
  </Line>
  <Line LineNo="3">
   <Item ID="ItemA7"/>
  </Line>
  <Line LineNo="4">
   <Item ID="ItemB3"/>
  </Line>
  <Line LineNo="5">
   <Item ID="ItemC1"/>
  </Line>
 </Lines>
</Order>

So after sorting the xml will look like

<Order>
 <Lines>
  <Line LineNo="1">
   <Item ID="ItemA1"/>
  </Line>
  <Line LineNo="5">
   <Item ID="ItemA4"/>
  </Line>
  <Line LineNo="4">
   <Item ID="ItemA7"/>
  </Line>
  <Line LineNo="3">
   <Item ID="ItemB3"/>
  </Line>
  <Line LineNo="2">
   <Item ID="ItemC1"/>
  </Line>
 </Lines>
</Order>

The logic I have written for this

Map<String, Element> mapIDAndLine = new HashMap<String, Element>();
NodeList nlLine = doc.getElementsByTagName("Line");
for(int cntLine = 0 ; cntLine < nlLine.getLength() ; cntLine++){

Element elLine = (Element) elLine.item(cntLine);
Element elItem = elLine.getChildElement("Item");

String sItemID = elItem.getAttribute("ID");

if(!mapIDAndLine.containsKey(sItemID )){

   mapIDAndLine.put(sItemID , elLine);

}



}

Map<String, String> treeMap = new TreeMap<String, String>(mapIDAndLine);

I get a map where the all the keys(ItemID) are sorted

Now I can iterate through the treeMap and get the corresponding lines and append to the doc after I have removed the original Lines.

Please let me know if I am doing something wrong here or there is a better way to do this .

Thanks in advance.

SMA_JAVA
  • 471
  • 4
  • 9
  • 18

0 Answers0