[英]iterating items with namespace prefix in XML using DOM4J
The problem is a namespace prefix. 问题是名称空间前缀。 The below is a sample xml code.
以下是示例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>
I would parse a xml code with Java and dom4j and print out something like; 我将使用Java和dom4j解析xml代码并打印出类似的内容;
Name File1 File2
ABC abc.htm abc.zip
CDF cdf.htm cfd.zip
Here's my Java code; 这是我的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" ???
}
There are several options, but here is one using XPath and namespace mappings: 有几个选项,但是这里是一个使用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);
}
A bit annoying that you cannot reuse the XPath instance as in javax.xml.xpath
. 有点烦人的是,您不能像
javax.xml.xpath
那样重用XPath实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.