dom4j解析带有命名空间的xml

xmlns是XML Namespaces的缩写

普通的xml解析:
xml示例:


    
        Good
    
    
        Better
    
    
        Best
    


dom4j:

Document resultDoc = null;
try {
	resultDoc = DocumentHelper.parseText(result);
} catch (DocumentException e) {
	e.printStackTrace();
}
Element rootEle = resultDoc.getRootElement();
List mesList = rootEle.selectNodes("//result/message");



带有xmlns的xml解析:
xml示例:


    
        Good
    
    
        Better
    
    
        Best
    


dom4j:

Document resultDoc = null;
try {
	resultDoc = DocumentHelper.parseText(result);
} catch (DocumentException e) {
	e.printStackTrace();
}
Element rootEle = resultDoc.getRootElement();
String nsUri = rootEle.getNamespaceURI();
Map nsMap = new HashMap();
nsMap.put("rootNs", nsUri);
XPath mesXpath = resultDoc.createXPath("//rootNs:result/rootNs:message");
mesXpath.setNamespaceURIs(nsMap);
List mesList = mesXpath.selectNodes(resultDoc);


当然,无论根节点有没有命名空间,第二种方式都适用。

 

你可能感兴趣的:(XML)