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;  
} 

 

相关文章:

  • 2022-03-01
  • 2021-12-16
  • 2022-12-23
  • 2022-12-23
  • 2021-07-20
  • 2022-12-23
  • 2022-01-29
  • 2021-10-03
猜你喜欢
  • 2021-08-28
  • 2022-12-23
  • 2021-10-27
  • 2021-09-11
  • 2022-12-23
  • 2021-07-14
相关资源
相似解决方案