JXPath
目次
概要
JavaBeans、Maps、サーブレットコンテキスト、DOMをXPathの仕様にしたがって取得できる。
非常に強力でおもしろい。SQLすきな人にもうけるかもしれない。
URL
http://jakarta.apache.org/commons/jxpath/
インストールと動作確認
jarをクラスパスのある場所におく。
commons-jxpath-1.1.jarを基に解説する。
testを動作させてみるとよい。
ソースからコンパイルする場合はMavenを利用するなら
maven dist
ですべてが一括で作成されて便利です。
利用方法
というかユーザガイド読めばたいがいわかると思います。
JavaBean Property Access
JXpathSample.java
public class JXpathSample {
public String getTitle() {
return "title";
}
public String[] getAuthorName() { String author[] = {"sakito", "python", "emacs"};
return author;
}
}
UseSample.java
import org.apache.commons.jxpath.*;
public class UseSample {
public static void main(String[] args) {
JXpathSample path = new JXpathSample();
JXPathContext context = JXPathContext.newContext(path);
String title = (String) context.getValue("title");
System.out.println(title);
// XPathの仕様では最初が1になります。
String author1 = (String) context.getValue("authorName[1]"); String author2 = (String) context.getValue("authorName[2]");
String author3 = (String) context.getValue("authorName[3]");
System.out.println(author1);
System.out.println(author2);
System.out.println(author3);
// 存在しない値にアクセスすると、JXPathExceptionが発生します。
//String author4 = (String) context.getValue("authorName[4]");
// 配列などの複値の場合はiterateで取ります。
Iterator authors = context.iterate("authorName[position() > 0]");
for (;authors.hasNext();) {
System.out.println(authors.next());
}
}
}
Nested Bean Property Access
Author.java
public class Author {
private String name;
public Author(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
JXpathSample.javaに追加
public Author getAuthor() {
Author author = new Author("sakito");
return author;
}
UseSample.javaに追加
String name = (String) context.getValue("author/name");
System.out.println(name);
Map Element Access
Author.javaに追加
public Map getAuthorInfo() {
Map info = new HashMap();
info.put("address", "toukyo japan");
info.put("tel", "03-xxxx-xxxx");
return info;
}
UseSample.javaに追加
// 文法1
String tel = (String) context.getValue("author/authorInfo/tel");
System.out.println(tel);
// 文法2
String address = (String) context.getValue("author[@name='authorInfo']/address");
System.out.println(address);
// この例ではどちらでも問題ないですが、どちらを利用するかは場合によります。
// XPathの仕様を参照してください。
Setting Properties
値の変更も可能です。
JxpathSample.javaに追加
private String price;
public String getPrice() {
return this.price;
}
public void setPrice(String price) {
this.price = price;
}
UseSample.java
context.setValue("price", "2000");
String price = (String) context.getValue("price");
System.out.println(price);
context.setValue("price", "3000");
price = (String) context.getValue("price");
System.out.println(price);
参考サイト
日本語のサイトはJakartaの杜の翻訳以外には今ないかも。
ってか強力なのでおそらく秘密です。
公開しないで利用してるのではなかろうか?
