import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Attribute;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
import org.jdom2.xpath.XPathFactory;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.filter.Filters;

public class MondialJDOMXPath {
  public static void main(String[] args) {
  try {
      SAXBuilder builder = new SAXBuilder();
      Document doc = (Document) builder.build(new File("../mondial.xml"));
      Element mondial = doc.getRootElement();
      XPathFactory xpf = XPathFactory.instance();



      XPathExpression xpath = xpf.compile("//country[@car_code='R']/@area");
      Attribute a = (Attribute) xpath.evaluateFirst(doc);     // -> casting
      int area = Integer.valueOf(a.getValue());
      System.out.println(area);

      xpath = xpf.compile("//country[@area > 7000000]/name");
      List<Object> names = xpath.evaluate(doc);   //  <Object> -> casting
      for (Object n : names) System.out.println(((Element) n).getTextTrim());

      Map<String,Object> vars = new HashMap<String,Object>();
      vars.put("code","D");
      XPathExpression<Element>   // due to filter: result type guaranteed
        xp2 = xpf.compile("//country[@car_code=$code]/population[last()]",
                          Filters.element(), vars, (Namespace[]) null);
      Element res = xp2.evaluateFirst(doc);  // no casting necessary
      int pop = Integer.valueOf(((Element)res).getTextTrim());
      System.out.println(pop);
      xp2.setVariable("code", "F");
      res = (Element) xp2.evaluateFirst(doc);
      pop = Integer.valueOf(((Element)res).getTextTrim());
      System.out.println(pop);
  } catch (Exception e) { e.printStackTrace(); }
}}
