/* * (C) Copyright IBM Corp. 2004. All rights reserved. * * US Government Users Restricted Rights Use, duplication or * disclosure restricted by GSA ADP Schedule Contract with IBM Corp. * * The program is provided "as is" without any warranty express or * implied, including the warranty of non-infringement and the implied * warranties of merchantibility and fitness for a particular purpose. * IBM will not be liable for any damages suffered by you as a result * of using the Program. In no event will IBM be liable for any * special, indirect or consequential damages or lost profits even if * IBM has been advised of the possibility of their occurrence. IBM * will not be liable for any third party claims against you. */ import java.io.File; import java.io.IOException; import java.util.List; import java.util.ListIterator; import org.jdom.DocType; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.jdom.output.XMLOutputter; public class JdomSorter { public static void main(String[] argv) { if (argv.length == 0 || (argv.length == 1 && argv[0].equals("-help"))) { System.out.println("\nUsage: java JdomSorter uri"); System.out.println(" where uri is the URI of your XML sonnet."); System.out.println(" Sample: java JdomSorter sonnet.xml"); System.out.println("\nUses the JDOM API to parse an XML sonnet, " + "sorts the lines of the sonnet,"); System.out.println("then writes the sorted sonnet " + "back to the console."); System.exit(1); } JdomSorter js = new JdomSorter(); js.parseAndSortLines(argv[0]); } public void parseAndSortLines(String uri) { try { SAXBuilder sb = new SAXBuilder(); Document doc = sb.build(new File(uri)); sortLines(doc); XMLOutputter xo = new XMLOutputter(); xo.setTrimAllWhite(true); xo.setIndent(" "); xo.setNewlines(true); xo.output(doc, System.out); } catch (Exception e) { e.printStackTrace(); } } public void sortLines(Document sonnet) { Element linesElement = sonnet.getRootElement(). getChild("lines"); List lines = linesElement.getChildren("line"); for (int i = 0; i < 14; i++) for (int j = 0; j < (14 - 1 - i); j++) if (((Element)lines.get(j)).getText(). compareTo(((Element)lines.get(j+1)).getText()) > 0) lines.add(j, lines.remove(j+1)); } }