问题是名称空间前缀。以下是xml代码示例。
<rss version="2.0">
<channel>
<item>
<ed:filing xmlns:ed="http://www.ed.com">
<ed:name>ABC</ed:name>
<ed:files>
<ed:file ed:id="1" ed:file="abc.htm" />
<ed:file ed:id="2" ed:file="abc.zip" />
</ed:files>
</ed:filing>
</item>
<item>
<ed:filing xmlns:ed="http://www.ed.com">
<ed:name>CDF</ed:name>
<ed:files>
<ed:file ed:id="1" ed:file="cdf.htm" />
<ed:file ed:id="2" ed:file="cdf.zip" />
</ed:files>
</ed:filing>
</item>
</channel>
</rss>
我会用Java和dom4j解析xml代码并打印出类似的内容;
Name File1 File2
ABC abc.htm abc.zip
CDF cdf.htm cfd.zip
这是我的Java代码;
SAXReader reader = new SAXReader();
Document document = reader.read( inputFile );
List<Node> nodes = document.selectNodes("//rss/channel/item");
for (Node node : nodes) {
??? How can I access "ed:name" and "ed:file" ???
}
答案 0 :(得分:1)
有几个选项,但这里有一个使用XPath和命名空间映射:
Map<String, String> nc = new HashMap<String, String>() {
{
put("ed", "http://www.ed.com");
}
};
System.out.printf("Name\tFile 1\tFile 2\n");
for (Node node : nodes) {
XPath xp = document.createXPath(".//ed:name");
xp.setNamespaceURIs(nc);
String name = xp.selectSingleNode(node).getText();
xp = document.createXPath(".//ed:file[@ed:id='1']/@ed:file");
xp.setNamespaceURIs(nc);
String f1 = xp.selectSingleNode(node).getText();
xp = document.createXPath(".//ed:file[@ed:id='2']/@ed:file");
xp.setNamespaceURIs(nc);
String f2 = xp.selectSingleNode(node).getText();
System.out.printf("%s\t%s\t%s\n", name, f1, f2);
}
有点烦人的是你不能像javax.xml.xpath
那样重用XPath实例。