Java HTML / XML How to - Parse this xml code and to get the values








Question

We would like to know how to parse this xml code and to get the values.

Answer

import java.util.Iterator;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
/* ww  w  .  j av a  2  s  . c  o m*/
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build("xml/board.xml");

    // search for x attribute
    XPathFactory xpfac = XPathFactory.instance();
    XPathExpression<Attribute> xp = xpfac.compile("//squareBumper/@x", Filters.attribute());
    List<Attribute> results = xp.evaluate(doc);

    Iterator<Attribute> iterator = results.iterator();

    // retreive all x attributes (y is similar)
    while (iterator.hasNext()) {
      Attribute a = iterator.next();
      System.out.println(a.getIntValue());
    }

}