del.icio.us API - PostのデータをXPathで取得 2008/04/27



PostのデータをXPathで取り出します。

  • 構造が単純なので素直にとって、自前のPostクラスに値を入れています。
  • Java標準のAPIを使っています。


以下、コード
/**
* Postのリストを作成します。
* @param xml
* @return
* @throws SAXException
* @throws IOException
* @throws ParserConfigurationException
* @throws XPathExpressionException
*/
static List<Post> toPosts(String xml) throws SAXException, IOException,
ParserConfigurationException, XPathExpressionException {

Document document = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(
new ByteArrayInputStream(xml.getBytes("utf-8")));
List<Post> list = new ArrayList<Post>();
XPath path = XPathFactory.newInstance().newXPath();

NodeList nodeList = (NodeList) path.evaluate("/posts/post", document,
XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Post post = new Post();
Node node = nodeList.item(i);
post.description = path.evaluate("@description", node);
post.href = path.evaluate("@href", node);
post.hash = path.evaluate("@hash", node);
post.others = path.evaluate("@others", node);
post.time = path.evaluate("@time", node);
String s = path.evaluate("@tag", node);
String[] tags = s.split(" ");
post.tag = Arrays.asList(tags);
list.add(post);
}

return list;
}

/**
*
* @author nakawakashigeto
*/
static class Post {
public String href = "";
public String description = "";
public String hash = "";
public String others = "";
public List<String> tag = new ArrayList<String>();
public String time = "";

public String toString() {
return String
.format(
"href:[%s] description:[%s] hash:[%s] others:[%s] tags:[%s] time:[%s]",
this.href, this.description, this.hash,
this.others, this.tag, this.time);
}
}

: