使用 DOM4J 的xpath 非常方便,但是,直接使用xpath 取带命名空间的xm文件,会出现取不到节点的问题.具体问题如下
<message id="oNVls-26" to="admin6@172.17.35.3" from="admin3@172.17.35.3/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 的值: 使用xpath expression : “/message/ext/identify ” 将不能取到值
取x的属性值 : 使用xpath expression: “/message/ext/identify/x/@var “; 也不能取到x var 的属性值
那么该怎么做了,直接上代码:
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)