JDOM を使用して XML ファイルを読み取り、XPath を使用して JDOM ドキュメントからデータを抽出したいと考えています。Document オブジェクトを正常に作成しますが、XPath を使用して Document に要素のリストをクエリしても、何も得られません。
私の XML ドキュメントには、ルート要素で定義されたデフォルトの名前空間があります。面白いことに、デフォルトの名前空間を削除すると、XPath クエリが正常に実行され、必要な要素が返されます。XPath クエリが結果を返すようにするには、他に何をする必要がありますか?
XML:
<?xml version="1.0" encoding="UTF-8"?>
<collection xmlns="http://www.foo.com">
<dvd id="A">
<title>Lord of the Rings: The Fellowship of the Ring</title>
<length>178</length>
<actor>Ian Holm</actor>
<actor>Elijah Wood</actor>
<actor>Ian McKellen</actor>
</dvd>
<dvd id="B">
<title>The Matrix</title>
<length>136</length>
<actor>Keanu Reeves</actor>
<actor>Laurence Fishburne</actor>
</dvd>
</collection>
ジャワ:
public static void main(String args[]) throws Exception {
SAXBuilder builder = new SAXBuilder();
Document d = builder.build("xpath.xml");
XPath xpath = XPath.newInstance("collection/dvd");
xpath.addNamespace(d.getRootElement().getNamespace());
System.out.println(xpath.selectNodes(d));
}