dom4j通过 xpath 处理xmlns

xml中含有命名空间后,用普通的xpath只能筛选到根结点

 

需要在map里加一个xml的namespace

Map map = new HashMap();
map.put("xmlns","http://docbook.org/ns/docbook");


reader.getDocumentFactory().setXPathNamespaceURIs(map);
		
FileInputStream fin = new FileInputStream(new File(absolutePath));
InputStreamReader is = new InputStreamReader(fin,"UTF-8");
Document document = reader.read(is);

然后再装载XML文件

编写xpath时要带要上xmlns

原来是这样写:document.selectNodes("/book/formerAidText/title")

加上xmlns后:document.selectNodes("/xmlns:book/xmlns:formerAidText/xmlns:title")

如果闲麻烦,加个正则替换

public static String fixedXpath(String xpath)  
{  
     xpath= xpath.replaceAll("/(\\w)", "/"+"xmlns:$1");//replace start with "/"  
     xpath= xpath.replaceAll("^(\\w)", "xmlns:$1");    //replace start with word  
     return xpath;  
} 

 

posted @ 2017-04-12 09:13  小小鬼  阅读(1215)  评论(0编辑  收藏  举报