Thursday, December 15, 2011

Java XML XPath


 
import org.apache.xml.dtm.ref.DTMNodeList;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
 
public class XPathTest extends TestCase {
    private static final String CAR_RECORDS = "<records>       <car name='HSV Maloo' make='Holden' year='2006'>         <country>Australia</country>         <record type='speed'>Production Pickup Truck with speed of 271kph</record>       </car>       <car name='P50' make='Peel' year='1962'>         <country>Isle of Man</country>         <record type='size'>Smallest Street-Legal Car at 99cm wide and 59 kg in weight</record>       </car>       <car name='Royale' make='Bugatti' year='1931'>         <country>France</country>         <record type='price'>Most Valuable Car at $15 million</record>       </car>     </records> ";
 
    public void test() throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputStream inputStream = new ByteArrayInputStream(CAR_RECORDS.getBytes());
        Element records = builder.parse(inputStream).getDocumentElement();
        XPath xpath = XPathFactory.newInstance().newXPath();
        DTMNodeList nodes = (DTMNodeList) xpath.evaluate("//car", records, XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength(); i++) {
            org.w3c.dom.Node node = nodes.item(i);
            String make = xpath.evaluate("@make", node);
            String country = xpath.evaluate("country/text()", node);
            String type = xpath.evaluate("record/@type", node);
            System.out.println(make + " of " + country + " has a " + type + " record");
        }
    }
 
}