dom4j 解析xml多层

阅读更多
dom4j解析多层xml  (此例子为网络摘抄)
例如有这么一个xml文件data4.xml





aaa


bbb




总共有4层,我们的目标是读取到username


package wzq.j2se.xml;


import java.util.Iterator;


import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;


public class Dom4j4 {
public static void main(String[] args) {
try{
InputSource is = new InputSource("http://localhost/data4.xml");
SAXReader reader = new SAXReader();  
reader.setEncoding("utf-8");
/*File f = new File("D:\\androidspace\\javanote\\src\\wzq\\j2se\\xml\\data4.xml"); 
Document doc = reader.read(f); */
Document doc = reader.read(is);
Dom4j4 j1 = new Dom4j4();
Element rootElt = doc.getRootElement(); // 获取根节点
        System.out.println("根节点:" + rootElt.getName()); // 拿到根节点的名称
        Iterator bbbb = rootElt.elementIterator("bbbb"); ///获取根节点下的子节点bbbb
           // 遍历bbbb节点
           while (bbbb.hasNext()) {
               Element recordEless = (Element) bbbb.next();
               Iterator cccc = recordEless.elementIterator("cccc"); // 获取子节点bbbb下的子节点cccc
               while (cccc.hasNext()) {
                   Element itemEle = (Element) cccc.next();
                   Iterator dddd = itemEle.elementIterator("dddd");
                   while(dddd.hasNext()){
                    Element tableItem = (Element) dddd.next();
                    String username = tableItem.elementTextTrim("username"); // 拿到dddd下的字节点username的值
                   System.out.println("username:" + username);
                   }
               }
           }
}catch(Exception e){
e.printStackTrace();
}
}
}

你可能感兴趣的:(xml)