一個用dom編寫的目錄樹形結構,請大家提提意見。

jander發表於2003-08-26
目錄可以在任何層次新增、刪除。

category.dtd

<?xml version="1.0"  encoding="GBK"?>
<!ELEMENT category ( category*)>
<!ATTLIST category
          id   ID  REQUIRED
          name  CDATA  REQUIRED
          locked (true|false) "false"
          disvisible (true|false) "false"
          level    CDATA  REQUIRED
>
<p class="indent">


category.xml

<?xml version="1.0"  encoding="GBK"?>
<!DOCTYPE category SYSTEM "category.dtd">
<category id="c0" name="category0" locked="false" disvisible="false" level="0">
    <category id="c1" name="category1" locked="false" disvisible="false" level="1"/>
</category>
<p class="indent">


CategoryDetail

import java.util.List;

public class CategoryDetail {
    private String id;
    private String name;
    private boolean locked;
    private boolean disvisible;
    private int level;
    private List parentList;//所有父親的集合,按繼承順序排列。
    private List childList;//所有孩子的集合

    public CategoryDetail(String id, String name, boolean locked, boolean disvisible, int level, List parentList, List childList) {
        this.id = id;
        this.name = name;
        this.locked = locked;
        this.disvisible = disvisible;
        this.level = level;
        this.parentList = parentList;
        this.childList = childList;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isLocked() {
        return locked;
    }

    public void setLocked(boolean locked) {
        this.locked = locked;
    }

    public boolean isDisvisible() {
        return disvisible;
    }

    public void setDisvisible(boolean disvisible) {
        this.disvisible = disvisible;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    public List getParentList() {
        return parentList;
    }

    public void setParentList(List parentList) {
        this.parentList = parentList;
    }

    public List getChildList() {
        return childList;
    }

    public void setChildList(List childList) {
        this.childList = childList;
    }

    public String printTag(int count,String tag){
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<count;i++){
            sb.append(tag);
        }
        return sb.toString();
    }

}

<p class="indent">


CategoryData

public class CategoryData {
    public static CategoryData Empty=new CategoryData();
    private String id;
    private String name;
    private boolean locked;
    private boolean disvisible;
    private int level;

    public CategoryData() {
    }

    public CategoryData(String id, String name, boolean locked, boolean disvisible, int level) {
        this.id = id;
        this.name = name;
        this.locked = locked;
        this.disvisible = disvisible;
        this.level = level;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isLocked() {
        return locked;
    }

    public void setLocked(boolean locked) {
        this.locked = locked;
    }

    public boolean isDisvisible() {
        return disvisible;
    }

    public void setDisvisible(boolean disvisible) {
        this.disvisible = disvisible;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    public String toString() {
        return "CategoryData: id="+id+"  name="+name;
    }
}

<p class="indent">


CategoryTree

import org.w3c.dom.*;

import javax.xml.parsers.*;
import java.io.*;
import java.util.*;

public class CategoryTree {
    private Document doc;
    private String xmlFile = "D:\\myapp\\xmltree\\build\\category.xml";
    private final static String ID_ATTR = "id";
    private final static String NAME_ATTR = "name";
    private final static String LOCKED_ATTR = "locked";
    private final static String DISVISIBLE_ATTR = "disvisible";
    private final static String LEVEL_ATTR = "level";
    private final static String CATEGORY_ELEMENT = "category";

    public CategoryTree() {
        load();
    }

    public CategoryDetail getCategoryDetail(String id) throws CategoryNotFoundException {
        Element element = doc.getElementById(id);
        if (element == null)
            throw new CategoryNotFoundException();
        return new CategoryDetail(
                id,
                element.getAttribute(NAME_ATTR),
                Boolean.getBoolean(element.getAttribute(LOCKED_ATTR)),
                Boolean.getBoolean(element.getAttribute(DISVISIBLE_ATTR)),
                Integer.parseInt(element.getAttribute(LEVEL_ATTR)),
                getParentList(element),
                getChildList(element)
        );
    }

    public CategoryData getCategoryData(String id) throws CategoryNotFoundException {
        Element element = doc.getElementById(id);
        if (element == null)
            throw new CategoryNotFoundException();
        else
            return new CategoryData(
                    id,
                    element.getAttribute(NAME_ATTR),
                    Boolean.getBoolean(element.getAttribute(LOCKED_ATTR)),
                    Boolean.getBoolean(element.getAttribute(DISVISIBLE_ATTR)),
                    Integer.parseInt(element.getAttribute(LEVEL_ATTR))
            );
    }

    public void createCategory(String name, String parentID) throws CategoryNotFoundException {
        Element parent = doc.getElementById(parentID);
        if (parent == null)
            throw new CategoryNotFoundException();
        int parentLevel = Integer.parseInt(parent.getAttribute(LEVEL_ATTR));
        Element element = doc.createElement(CATEGORY_ELEMENT);
//測試時,用時間作ID.
        element.setAttribute(ID_ATTR, "c" + String.valueOf(System.currentTimeMillis()));
        element.setAttribute(NAME_ATTR, name);
        element.setAttribute(LOCKED_ATTR, "true");
        element.setAttribute(DISVISIBLE_ATTR, "true");
        element.setAttribute(LEVEL_ATTR, String.valueOf(++parentLevel));
        parent.appendChild(element);
        store();
    }

    public void removeCategory(String id) throws CategoryNotFoundException {
        Element element = doc.getElementById(id);
        if (element == null)
            throw new CategoryNotFoundException();
        Node parent = element.getParentNode();
        parent.removeChild(element);

        store();
    }

    private void load() {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(true);
            factory.setNamespaceAware(false);
            factory.setIgnoringElementContentWhitespace(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.parse(new File(xmlFile));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("can not load xml resource.");
        }
    }

    private void store() {
        try {
            //實現一個DOMSerializer類,來儲存xml。
            DOMSerializer serializer = new DOMSerializer("GBK");
            serializer.serialize(doc, new File(xmlFile));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private List getChildList(Element element) {
        List childList = new ArrayList();
        NodeList nodeList = element.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element child = (Element) node;
                childList.add(
                        new CategoryData(
                                child.getAttribute(ID_ATTR),
                                child.getAttribute(NAME_ATTR),
                                Boolean.getBoolean(child.getAttribute(LOCKED_ATTR)),
                                Boolean.getBoolean(child.getAttribute(DISVISIBLE_ATTR)),
                                Integer.parseInt(child.getAttribute(LEVEL_ATTR))
                        )
                );
            }
        }
        return childList;
    }

    private List getParentList(Element element) throws CategoryNotFoundException {
        int level = Integer.parseInt(element.getAttribute("level"));
        LinkedList parentList = new LinkedList();
        Element tmp = null;
        for (int i = 0; i < level; i++) {
            tmp = (Element) element.getParentNode();
            parentList.addFirst(getCategoryData(tmp.getAttribute("id")));
            element = tmp;
        }
        return parentList;
    }

    public static void main(String[] args) throws Exception {

        CategoryTree tree = new CategoryTree();
        long start = System.currentTimeMillis();
        tree.createCategory("我的文件", "c0");
        tree.removeCategory("c3");
        CategoryDetail c = tree.getCategoryDetail("c0");


        Iterator iter = c.getChildList().iterator();
        while (iter.hasNext()) {
            System.out.println(iter.next());
        }

        long end = System.currentTimeMillis() - start;
        System.out.println("run :" + end + " ms");
    }
}
<p class="indent">

相關文章