默认XML命名空间,JDOM和XPath [英] Default XML namespace, JDOM, and XPath

查看:118
本文介绍了默认XML命名空间,JDOM和XPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用JDOM读取XML文件,然后使用XPath从JDOM Document中提取数据。它创建了Document对象,但是当我使用XPath查询Document的元素列表时,我什么都没得到。

I want to use JDOM to read in an XML file, then use XPath to extract data from the JDOM Document. It creates the Document object fine, but when I use XPath to query the Document for a List of elements, I get nothing.

我的XML文档中定义了一个默认的命名空间根元素。有趣的是,当我删除默认命名空间时,它成功运行XPath查询并返回我想要的元素。我还需要做些什么才能让我的XPath查询返回结果?

My XML document has a default namespace defined in the root element. The funny thing is, when I remove the default namespace, it successfully runs the XPath query and returns the elements I want. What else must I do to get my XPath query to return results?

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>

Java:

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


推荐答案

XPath 1.0 不支持默认命名空间的概念( XPath 2.0 确实如此)。
任何未加前缀的标记总是被假定为无名称命名空间的一部分。

XPath 1.0 doesn't support the concept of a default namespace (XPath 2.0 does). Any unprefixed tag is always assumed to be part of the no-name namespace.

使用 XPath 1.0 时,你需要这样的东西:

When using XPath 1.0 you need something like this:

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

这篇关于默认XML命名空间,JDOM和XPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆