我有一个XML文件,如下所示:
<Elements name="Entities" xmlns="XS-GenerationToolElements">
Run Code Online (Sandbox Code Playgroud)
我将不得不打开很多这些文件.每个命名空间都有不同的命名空间,但一次只有一个命名空间(我永远不会在一个xml文件中找到两个命名空间).
使用XPath我想有一种自动方式将给定的命名空间添加到命名空间管理器.到目前为止,我只能通过解析xml文件来获取命名空间,但我有一个XPathNavigator实例,它应该有一个很好的,干净的方式来获取命名空间,对吧?
- 要么 -
鉴于我只有一个命名空间,以某种方式使XPath使用xml中唯一存在的命名空间,从而通过始终附加命名空间来避免混乱代码.
我想使用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>
Run Code Online (Sandbox Code Playgroud)
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));
}
Run Code Online (Sandbox Code Playgroud)