默认XML命名空间,JDOM和XPath

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

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

XML:

   Lord of the Rings: The Fellowship of the Ring 178 Ian Holm Elijah Wood Ian McKellen   The Matrix 136 Keanu Reeves Laurence Fishburne   

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时,你需要这样的东西:

 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代码段。

 for (Element el : doc.getRootElement().getDescendants(new ElementFilter())) { if (el.getNamespace() != null) el.setNamespace(null); } 

删除所有命名空间后,我可以使用简单的getChild(“elname”)样式导航或简单的XPath查询。

我不推荐这种技术作为一般解决方案,但在我的情况下它绝对有用。

您还可以执行以下操作

/*[local-name() = 'collection']/*[local-name() = 'dvd']/

以下是有用的xpath查询列表。