转: 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)

相关推荐