Thursday, 29 September 2011

Java-XML - Reverse the order of child elements

The below sample program will tell you how to reverse the order of child elements.


private void reverseChildElements() {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  Document doc = null;
  try {
  DocumentBuilder builder = factory.newDocumentBuilder();
        //Parse the input xml file
doc = builder.parse("src/xml/input_reverse.xml");
Node firstChild = doc.getFirstChild();
        // Get the child nodes which we want to reverse
NodeList childNodes = firstChild.getChildNodes();
Stack<Node> nodeStack = new Stack<Node>();
        // Put all the nodes into a Stack
for(int i = 0; i < childNodes.getLength(); i++) {
nodeStack.push(childNodes.item(i));
}
        // Remove the nodes and add the one which we get from pop().
        //This is the last one which we entered
while(!nodeStack.empty()) {
firstChild.appendChild(firstChild.removeChild(nodeStack.pop()));
}
doc.replaceChild(firstChild, doc.getFirstChild());
outputXml(doc, "output_reverse_elements.xml");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

No comments:

Post a Comment