dom4j获取指定节点数据

现在我有一个xml,如下

String xml = "<message id='GnIWm-10' to='jiangwan@dison-pc' from='test06@dison-pc/Smack' type='chat'><body/><thread>9dO8t1</thread><properties xmlns='http://www.jivesoftware.com/xmlns/xmpp/properties'><property><name>requestmenu</name><value type='string'/></property></properties></message>";

 在网上搜索的时候,发现dom4j,可以使用如下方法:

Document doc = DocumentHelper.parseText(xml);
List<org.dom4j.Element> list = doc.selectNodes(nodeName);

 按照网上的说法,我能获取message 下的子节点body和thread两个,但就是无法获取到properties,它们之间的区别只是多了xmlns而已。代码如下

Document doc = DocumentHelper.parseText(xml);
List<org.dom4j.Element> list doc.selectNodes("/message/body");

 最后发现,dom4j本身有一个方法获取其path(getUniquePath)。我通过一层层获取其path知道了他的具体地址:

Document doc = DocumentHelper.parseText(xml);
List<org.dom4j.Element> list = doc.selectNodes("/message/*[name()='properties']/*[name()='property']/*[name()='name']");

 最后样例如下:

private static void selectXML() throws Exception{
		String xml = "<message id='GnIWm-10' to='jiangwan@dison-pc' from='test06@dison-pc/Smack' type='chat'><body/><thread>9dO8t1</thread><properties xmlns='http://www.jivesoftware.com/xmlns/xmpp/properties'><property><name>requestmenu</name><value type='string'/></property></properties></message>";
		Document doc = DocumentHelper.parseText(xml);
		List<org.dom4j.Element> list = doc.selectNodes("/message/*[name()='properties']/*[name()='property']/*[name()='name']");
		for (org.dom4j.Element element : list) {
			System.out.println("name : "+ element.getName() + "->UniquePath:" + element.getUniquePath() + "->value:"+element.getTextTrim());
		}
	}

 

 

你可能感兴趣的:(xml,dom4j)