Xml转换为java List

package com.netstar8.dao.test;

 

import java.io.File;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

 

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

 

import org.w3c.dom.Document;

import org.w3c.dom.NamedNodeMap;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

 

import com.netstar8.pojos.tree.BaseNode;

 

public class XmlToJavaList {

 

    static Document doc;// 声明xml文件

    static List<BaseNode> tree = new ArrayList<BaseNode>();

   

    public static void main(String[] args) {

       executeXml2List();

    }

 

    private static void executeXml2List() {

       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

 

       dbf.setIgnoringComments(true);

       dbf.setIgnoringElementContentWhitespace(true);

      

       try {

           DocumentBuilder db = dbf.newDocumentBuilder();

           doc = db.parse(new File("E:\\tree.xml"));

           toTrans();

           showNewTree();

       } catch (ParserConfigurationException e) {

           e.printStackTrace();

       } catch (SAXException e) {

           e.printStackTrace();

       } catch (IOException e) {

           e.printStackTrace();

       }

    }

 

    private static void showNewTree() {

       BaseNode node;

       for(int m=0;m<tree.size();m++){

           node = tree.get(m);

           System.out.println("id:"+node.getId()+"\n");

       }

    }

 

    private static void toTrans() {

      

       BaseNode node;

       NodeList tagNodes = doc.getElementsByTagName("item");

       for (int i = 0; i < tagNodes.getLength(); i++) {

 

           NamedNodeMap atts = tagNodes.item(i).getAttributes();

           node = new BaseNode();

           for(int l=0;l<atts.getLength();l++){

             

              Node att = atts.item(l);

              if(att.getNodeName().equals("id")){

                  node.setId(Long.parseLong(att.getNodeValue()));

              }else if(att.getNodeName().equals("text")){

                  node.setName(att.getNodeValue());

              }

              System.out.println("atts"+l+":"+att.getNodeName()+"="+att.getNodeValue());

           }

           tree.add(node);

       }

    }

 

}

 tree.xml

<?xml version='1.0' encoding='iso-8859-1'?>
<tree id="0">
    <item id="1" text="t2">
    <item id="2" text="lb1" >    
    </item>    
    <item id="3" text="ts1" >    
    </item>    
    </item>
</tree>
lunzi   2007-09-21 18:18:16 评论:0   阅读:393   引用:0

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

验证码: (如不清楚,请刷新)

Copyright@2008 powered by YuLog