JDOM Distilled 
  
作者:  Tnk Luo 
  
“C++的发明人在使用C++上不一定会比使用C++的开发者厉害,UML的发明人在使用UML上不一定有Martin Fowler牛!” 
  
碰到了,XML,是不是也是如此呢? 
  
经济学中有,80/20规律。如何满足这80的要求,这就是JDOM最开始出现的理由。Java本身的学起来很简单,但用于操作XML的JAXP用起来不是那么简单(因为为了实现80 + 20的目的)。充分利用Java语言优势、比如,Java Collection Framework,学习曲线特别清晰。同时,JDOM很好的和现有的标准,比如SAX、DOM,实现了互操作。同时,JDOM可以以轻量级的方式操作XML数据,而且还避免了操作的复杂性、大量消耗内存的可能性,这正是现有操作XML 数据的API的缺陷。 
  
(JDOM本身所处的状态,以及相关的内容在文中不给出。您可以参考文中给出的参考资料。本文仅仅给出几个应用实例!) 
  
JDOM模型: 
  
具体细节,请参考 
http://www.cafeconleche.org/books/xmljava/chapters/ch15.html  
其中有一点需要大家注意:JDOM把XML中的成分,比如,元素名称、属性、。。。都用对象来操作!!! 
  
JDOM实例程序、思路。 
  
(1)       生成一个XML文件:这个很好实现! 
(2)       读取一个XML文件: 
  
        这两部分就不给出代码了。自己找找看。 
  
(3)       遍历一个XML文件: 
  
            private static void listChildren(Element current, int depth) 
        { 
                java.util.List children = current.getChildren(); 
                Iterator iterator = children.iterator(); 
                while (iterator.hasNext()) { 
                  Element child = (Element) iterator.next(); 
                  listChildren(child, depth+1); 
                } 
         } 
  
(4)       将一个XML文件写入到JTree相应的节点中: 
    我想这个,实现过程一定要用到什么呢?递归?(下面的代码不是我写的!大家分析分析,感觉还不错!) 
  
            private void buildTree(JDOMNode node, DefaultMutableTreeNode treeNode) { 
            // If this is a whitespace node or unhandled node, ignore it 
            if ((node == null) || (node.toString().trim().equals(""))) { 
                return; 
            } 
//            System.out.println(((ElementNode)node).getNodeName()); 
            DefaultMutableTreeNode newTreeNode = new  
DefaultMutableTreeNode(((ElementNode)node).getNodeName()); 
  
            // Walk over the children of the node 
            Iterator i = node.iterator(); 
            while (i.hasNext()) { 
                // Create JDOMNodes on the children and add to the tree 
                JDOMNode newNode = createNode(i.next()); 
                buildTree(newNode, newTreeNode); 
            } 
  
            // After all the children have been added, connect to the tree 
            treeNode.add(newTreeNode); 
        } 
  
(5)       将JTree中的节点写入到一个XML文件中: 
  
    借助于java.beans.XMLEncoder(在J2SE 1.4引入的,这一点要谢谢网友masterz!!!)。 
  
详细过程在这个地方有,有兴趣的可以去看看!! 
  
http://expert.csdn.net/Expert/topic/1202/1202913.xml?temp=.7047083 
  
所以: 
  
“JAXP不一定有JDOM好用!” 
  
参考资料: 
  
1.       http://www.jdom.org  
2.       http://xml.apache.org  
3.       http://java.sun.com/xml/  
4.       http://www.oreilly.com/catalog/javaxml2/          
<Java & XML, 2nd Edition>,Brett McLaughlin 
5.       http://www.cafeconleche.org/books/xmljava/chapters/index.html  
        <Processing XML with Java>,Elliotte Rusty Harold  
 
  |