XML

HelloHttpClientXMLMain

Apache HTTP Client と XPATH の合わせ技。

■前提

http://localhost:8080/myweb/cars.xml に以下のXMLがあるとする。

■XML

<?xml version="1.0" encoding="UTF-8"?>

<cars>

<car vin="123fhg5869705iop90">

<make>Toyota</make>

<model>Prius</model>

<year>2010</year>

<color>while</color>

</car>

<car vin="1G4AH59H45G118341">

<make>Honda</make>

<model>Fit</model>

<year>2011</year>

<color>green</color>

</car>

</cars>

■コード

package hello.org.apache.commons.httpclient;

import java.io.IOException;

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 org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.HttpException;

import org.apache.commons.httpclient.HttpMethod;

import org.apache.commons.httpclient.methods.GetMethod;

import org.w3c.dom.Document;

import org.xml.sax.SAXException;

public class HelloHttpClientXMLMain {

public static void main(String[] args) {

String url = "http://localhost:8080/myweb/cars.xml";

HttpClient client = new HttpClient();

HttpMethod method = new GetMethod(url);

try {

client.executeMethod(method);


Document doc = DocumentBuilderFactory.newInstance()

.newDocumentBuilder().parse(method.getResponseBodyAsStream());


// メーカーが Honda である model の取得

String xpathExpression = "/cars/car[make/text()='Honda']/model/text()";

XPath xpath = XPathFactory.newInstance().newXPath();

String text = (String) xpath.evaluate(xpathExpression, doc,

XPathConstants.STRING);


System.out.println(text);


} catch (HttpException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

} catch (ParserConfigurationException e) {

e.printStackTrace();

} catch (XPathExpressionException e) {

e.printStackTrace();

} finally {

method.releaseConnection();

client.getHttpConnectionManager().closeIdleConnections(0);

}

}

}

■結果

Fit