Example: Sorting XML

First, implement a Comparator:
  import dk.brics.xact.*;
  import java.util.*;

  public class RecipeComparator implements Comparator {         
      public int compare(Object o1, Object o2) {
          XML x1 = (XML)o1;
          XML x2 = (XML)o2;
          String s1 = x1.select("/recipe/title/text()")[0].text();
          String s2 = x2.select("/recipe/title/text()")[0].text();
          return s1.compareTo(s2);
      }

      public boolean equals(Object o1, Object o2) {
          XML x1 = (XML)o1;
          XML x2 = (XML)o2;
          String s1 = x1.select("/recipe/title/text()")[0].text();  
          String s2 = x2.select("/recipe/title/text()")[0].text();
          return s1.equals(s2);
      }
  }
      

Then the task is solved by
  
  import dk.brics.xact.*;
  import java.util.*;

  public class XactSort {
      public static void main(String[] args) {
          XML.setDefaultXPathNamespace("http://www.brics.dk/ixwt/recipes");

          // Load collection from external file
          XML collection = null;
          try {
              collection = 
                XML.get(args[0], 
                        "http://www.brics.dk/~amoeller/talks/xact/recipes.dtd", 
                        "http://www.brics.dk/ixwt/recipes");
          } catch (IOException e) {
              e.printStackTrace();
              System.exit(-1);
          }

          // Remove the recipes from the collection
          XML[] recipes = collection.select("/collection/recipe");
          collection = collection.gapify("/collection/recipe", "r");  

          // Sort by title and insert sorted collection
          Arrays.sort(recipes, new RecipeComparator());
          collection = collection.plug("r",recipes);

          // Validate and print
          collection.analyze("http://www.brics.dk/~amoeller/talks/xact/recipes.dtd", 
                             "http://www.brics.dk/ixwt/recipes");
          System.out.println(collection);
      }
  }