当我们解析xml的时候,如果该xml没有带命名空间,那么很好解析,直接用dom4j的selectNodes(XPath表达式)既可以了。但是如果命名空间那么则会返回空。下面为大家介绍三种方法来解决:
第一种:
<report xmlns="http://www.eclipse.org/birt/2005/design" version="3.2.15" id="1">
<list-property name="cssStyleSheets">
<structure>
<property name="fileName">D: eport.css</property>
</structure>
</list-property>
</report>
<list-property name="cssStyleSheets">
<structure>
<property name="fileName">D: eport.css</property>
</structure>
</list-property>
</report>
第一个方案.设置你的xpath的命名空间setNamespaceURI
public class TransferXML {
public static void main(String[] args) throws Exception
{
Map map = new HashMap();
SAXReader saxReader = new SAXReader();
File file = new File("D:\test.xml");
Document document = saxReader.read(file);
public static void main(String[] args) throws Exception

Map map = new HashMap();
SAXReader saxReader = new SAXReader();
File file = new File("D:\test.xml");
Document document = saxReader.read(file);
String xmlNameSpace=c.getRootElement().getNamespaceURI();//取得命名空间
map.put("design","http://www.eclipse.org/birt/2005/design");//设置xml的命名空间
XPath x = document.createXPath("//design:list-property");//填写XPath表达式
x.setNamespaceURIs(map);//设置命名空间
List nodelist = x.selectNodes(document);//取出符合规定的集合
System.out.println(nodelist.size());
}
}
第二种:设置你的DocumentFactory()的命名空间 setXPathNamespaceURIs
public class TransferXML {
public static void main(String[] args) throws Exception{
Map map = new HashMap();
map.put("design","http://www.eclipse.org/birt/2005/design");//填充map
SAXReader saxReader = new SAXReader();
File file = new File("D:\test.xml");
saxReader.getDocumentFactory().setXPathNamespaceURIs(map);//设置命名空间
Document document = saxReader.read(file);
List tmp = document.selectNodes("//design:list-property");//用XPath选取节点
System.out.println(tmp.size());
}
}
public static void main(String[] args) throws Exception{
Map map = new HashMap();
map.put("design","http://www.eclipse.org/birt/2005/design");//填充map
SAXReader saxReader = new SAXReader();
File file = new File("D:\test.xml");
saxReader.getDocumentFactory().setXPathNamespaceURIs(map);//设置命名空间
Document document = saxReader.read(file);
List tmp = document.selectNodes("//design:list-property");//用XPath选取节点
System.out.println(tmp.size());
}
}
详细请参考:http://blog.sina.com.cn/s/blog_4bf2e5550100sbb7.html