13

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));
}
4

3 に答える 3

26

XPath 1.0は、デフォルトの名前空間の概念をサポートしていません(XPath 2.0はサポートしています)。接頭辞のないタグは、常に名前のない名前空間の一部であると見なされます。

XPath 1.0を使用する場合は、次のようなものが必要です。

public static void main(String args[]) throws Exception {
    SAXBuilder builder = new SAXBuilder();
    Document d = builder.build("xpath.xml");
    XPath xpath = XPath.newInstance("x:collection/x:dvd");
    xpath.addNamespace("x", d.getRootElement().getNamespaceURI());
    System.out.println(xpath.selectNodes(d));
}
于 2009-02-12T20:36:35.310 に答える