转: dom4j中使用xpath解析带命名空间的xml文件,取不到节点的解决办法
哎基础不扎实啊~~~DOM4J取了一个小时没取出来郁闷坏了。。
引用
使用DOM4J的xpath非常方便,但是,直接使用xpath取带命名空间的xm文件,会出现取不到节点的问题.具体问题如下
Xml文档代码<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的属性值
那么该怎么做了,直接上代码:
Java代码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(ExtremeXML)
相关推荐
Andrewjdw 2020-05-29
与卿画眉共浮生 2020-10-14
xiyang 2020-08-21
XGQ 2020-07-04
Yakamoz 2020-05-26
行吟阁 2020-05-18
88491874 2020-04-30
baijinswpu 2020-07-29
leonranri 2020-07-26
zhongliwen 2020-07-05
麋鹿麋鹿迷了路 2020-07-05
zengyu00 2020-07-05
CoderBoy 2020-06-28
whbing 2020-06-28
绝望的乐园 2020-06-27
wellfly 2020-06-26
菇星獨行 2020-06-25
草原孤狼 2020-06-25
坚持着执着 2020-06-16