java使用dom4j解析xml(通用)

xml样例如下


        a
        
              b
              
                     c
                          ...
              
        

dom4j jar包下载地址
     https://dom4j.github.io/

解析xml代码

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import java.util.Iterator;

public void test(){

    Document document = DocumentHelper.parseText(result);
    Element rootElement = document.getRootElement();
    Iterator iter = rootElement.elementIterator("result");
    String a="";
    String b="";
    String c="";
    while (iter.hasNext()) {
        Element recordEle = (Element) iter.next();
        a=recordEle.elementTextTrim("A");
        Iterator iterMes = recordEle.elementIterator("Test");
        while (iterMes.hasNext()) {
            Element itemEle = (Element) iterMes.next();
            b=itemEle.elementTextTrim("B");
            Iterator iterLast = itemEle .elementIterator("Test1");
            while (iterLast.hasNext()) {
                Element itemEle = (Element) iterLast.next();
                c=itemEle.elementTextTrim("C");
            }   
        }
    }
    System.out.println(a);
    System.out.println(b);
    System.out.println(b);
}

 

你可能感兴趣的:(Java)