java解析xml,如何拿到Test节点下所有子节点的Text
xml结构如下所示,假设Test节点下面只有一层节点了,意思 就是A、B、C下面不再有子节点 <Test> <A>123</A> <B>456</B> <C>789</C> </Test>
如何通过Test节点,直接拿到123,456,789 而不是通过A,B,C去拿? jdom2能不能实现这样的操作? package test.xml;
import java.util.List;
import org.dom4j.Document; import org.dom4j.Node; import org.dom4j.io.SAXReader;
/** * 需要的jar包为:dom4j.jar * @author Administrator * */ public class XmlUtilsDom4j {
public static void main(String args[]) { XmlUtilsDom4j.xml2ModelNode(); }
public static void xml2ModelNode() { String path = "/resources/ehcache/ehcache.xml"; System.out.println("开始加载客户化配置文件。path=" + path); System.out.println("真实地址:"+XmlUtilsDom4j.class.getResource(path)); SAXReader reader = new SAXReader(); Document doc;
try { doc = reader.read(XmlUtilsDom4j.class.getResourceAsStream(path)); //fist List<Node> nodes = null; nodes = doc.selectNodes("/ehcache/cache"); System.out.println(nodes.size()); for(Node node : nodes) { System.out.println(node.asXML()); System.out.println(node.getStringValue()); System.out.println(node.valueOf("@name")); }
}catch (Exception e) { // TODO: handle exception } }
} XPath: /Test/*/text()
|