本帖最后由 u012748297 于 2014-01-27 16:15:16 编辑

解决方案 »

  1.   

    直接贴代码
    import java.math.BigDecimal;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;import com.sun.org.apache.regexp.internal.recompile;
    import com.yxd.pris.model.TVideo;/**
     *功能说明:
     *
     *创建人: 刘飞
     *
     *创建时间:2014-1-27 下午04:58:49
     *
     *修改人             修改时间             修改描述
     *
     *
     *Copyright (c)2014 
     * 
     */
    public class Node {
    private String text;
    private List children;
    public String getText() {
    return text;
    }
    public void setText(String text) {
    this.text = text;
    }
    public List getChildren() {
    return children;
    }
    public void setChildren(List children) {
    this.children = children;
    }
    public static void main(String[] args) {
    String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
    "<resources>" +
    "<resource name=\"level1\" >" +
    "<resource name=\"level2\" >" +
    " <resource name=\"level3\" >" +
    "</resource>" +
    "</resource>" +
    "</resource>" +
    "<resource name=\"text1\" />" +
    "</resources>";
    Document doc = null;
    try {
    doc = DocumentHelper.parseText(xml);
    Element rootElt = doc.getRootElement(); // 获取根节点
    Node node = new Node();
    node.setText(rootElt.attributeValue("name"));
    node.recursiveXML(rootElt, 0, node);
    } catch (DocumentException e) {
    e.printStackTrace();
    } // 将字符串转为XML
            
    }

    private void recursiveXML(Element element,int next,Node node) {
    node.children = new ArrayList<Node>();
    String url ="/";
    for (int i = 0; i < next; i++) {
    url = url+"/resource";
    }
    next++;
    List list = element.selectNodes(url);
    if (list.size() > 0 ) {
    Iterator resource = element.elementIterator("resource"); //获取根节点下的子节点resource
               //遍历zone节点
               while (resource.hasNext()) {
                Element resourceEle = (Element) resource.next();
            String resourceName = resourceEle.attributeValue("name");
            Node childNode = new Node();
            childNode.setText(resourceName);
            node.children.add(childNode);
                   recursiveXML(resourceEle,next,childNode);
               }
    }
    }
    }