dom4j中使用xpath解析带命名空间的xml文件,取不到节点的解决办法
使用 DOM4J 的xpath 非常方便,但是,直接使用xpath 取带命名空间的xm文件,会出现取不到节点的问题.具体问题如下
<message id="oNVls-26" to="[email protected]" from="[email protected]/Smack" type="chat"> <subject>zscasvgsadg</subject> <body>sdvgsdvsaddzsfbnzsdfbvdas</body> <thread>0pMmg6</thread> <ext xmlns="infoair:obcs:msg:ext"> <identify>1306663476453admin38</identify> <sendType>NOR</sendType> <awokeTime>60</awokeTime> <x xmlns="infoair:obcs:msg:source" var="130666347645334345"/></ext> </message>
如果想取
identify的值:使用xpathexpression:“/message/ext/identify”将不能取到值
取x的属性值:使用xpathexpression:“/message/ext/identify/x/@var“;也不能取到xvar的属性值
那么该怎么做了,直接上代码:public static MessageNode getNode1(String msg) throws DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(msg)); XPath xPath = document.createXPath("/message/a:ext/a:identify"); Map<String, String> names = new HashMap<String, String>(); names.put("a", "infoair:obcs:msg:ext"); MessageNode messageNode = new MessageNode(); xPath.setNamespaceURIs(names); Node node = xPath.selectSingleNode(document); messageNode.setIdentify(node.getText()); xPath = document.createXPath("/message/a:ext/b:x/@var"); names.put("b", "infoair:obcs:msg:source"); xPath.setNamespaceURIs(names); node = xPath.selectSingleNode(document); messageNode.setParentId(node.getText()); return messageNode; }
names.put("a", "infoair:obcs:msg:ext");
只要 xpath 选择时,加上命名空间就行了
"a"表示前缀,"infoair:obcs:msg:ext"表示命名空间。
具体原因,请见:
XML 命名空间以及它们如何影响 XPath 和 XSLT (Extreme XML)相关推荐
Andrewjdw 2020-05-29
realhero 2014-04-30
kenvie 2012-06-13
paleyellow 2020-10-25
baifanwudi 2020-10-25
LxyPython 2020-08-17
fangjack 2020-06-25
云之高水之远 2020-06-20
maowenbei 2020-06-10
tiankele0 2020-06-09
zengni 2020-05-29
Alanxz 2020-05-28
yogoma 2020-05-28
freerocker 2020-05-26
andrewwf 2020-05-08
我欲疾风前行 2020-04-30
坚持是一种品质 2020-04-25