Java產生XML檔案

來源:互聯網
上載者:User

標籤:list   stat   private   檔案   driver   nbsp   drive   exception   end   

我們在資料庫中的資料可以將其提取出來產生XML檔案,方便傳輸。例如資料庫中有Admin這張表:

我們寫一個java類表示admin資料:

 1 package xmlDom.vo; 2   3 import java.io.Serializable; 4 import java.util.Date; 5 import java.util.List; 6  7 public class Admin implements Serializable 8 { 9     private String aid;10     private String password;11     private Integer rid;12     private Integer type;13     private Date lastdate;14     private Integer flag ; 15      16     17  18  19     public Integer getRid()20     {21         return rid;22     }23     public void setRid(Integer rid)24     {25         this.rid = rid;26     }27     public String getAid()28     {29         return aid;30     }31     public void setAid(String aid)32     {33         this.aid = aid;34     }35     public String getPassword()36     {37         return password;38     }39     public void setPassword(String password)40     {41         this.password = password;42     }43     public Integer getType()44     {45         return type;46     }47     public void setType(Integer type)48     {49         this.type = type;50     }51     public Date getLastdate()52     {53         return lastdate;54     }55     public void setLastdate(Date lastdate)56     {57         this.lastdate = lastdate;58     }59     public Integer getFlag()60     {61         return flag;62     }63     public void setFlag(Integer flag)64     {65         this.flag = flag;66     } 67     68 }

然後通過JDBC 將表中的資料轉換成一個鏈表:

 1 package xmlDom.dbc; 2  3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.SQLException; 6  7 public class DatabaseConnection 8 { 9     private static final String MYSQLDRIVER = "org.gjt.mm.mysql.Driver";10     private static final String MYSQLURL = "jdbc:mysql://localhost:3306/hrdb";11     private static final String USERNAME = "root";12     private static final String PASSWORD = "admin";13 14     private Connection conn;15 16     public DatabaseConnection()17     {18         try19         {20             Class.forName(MYSQLDRIVER);21             this.conn = DriverManager.getConnection(MYSQLURL, USERNAME, PASSWORD);22         } catch (Exception e)23         {24             e.printStackTrace();25         }26     }27 28     public Connection getConnection() throws Exception29     {30         if (null != this.conn)31             return this.conn;32         else33             throw new Exception("擷取資料庫連接失敗");34     }35 36     public void close()37     {38         if (null != this.conn)39         {40             try41             {42                 this.conn.close();43             } catch (SQLException e)44             {45                 e.printStackTrace();46             }47         }48     }49 }
    public static List<Admin> loadFromDB() throws Exception    {        List<Admin> allAdmins = new ArrayList<Admin>();                DatabaseConnection dbc = new DatabaseConnection();        Connection conn = dbc.getConnection();        PreparedStatement ps = conn.prepareStatement("SELECT aid,rid,type,lastdate,flag FROM admin");        ResultSet rs = ps.executeQuery();        while(rs.next())        {            Admin vo = new Admin();                        vo.setAid(rs.getString("aid"));            vo.setRid(rs.getInt("rid"));            vo.setType(rs.getInt("type"));            vo.setLastdate(rs.getDate("lastdate"));            vo.setFlag(rs.getInt("flag"));                        allAdmins.add(vo);        }                return allAdmins;    }

然後將該鏈錶轉換成記憶體中的XML結構:

    public static Document getDocument( List<Admin> allAdmins) throws Exception    {        DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();        DocumentBuilder documentBuilder = dbfactory.newDocumentBuilder();        Document document = documentBuilder.newDocument();                Element root = document.createElement("admins");                for(Admin item : allAdmins)        {            Element admin = document.createElement("admin");            admin.setAttribute("aid", item.getAid());                        Element rid = document.createElement("rid");            rid.appendChild(document.createTextNode(String.valueOf(item.getRid())));                        Element type = document.createElement("type");            type.appendChild(document.createTextNode(String.valueOf(item.getType())));                        Element lastdate = document.createElement("lastdate");            lastdate.appendChild(document.createTextNode(String.valueOf(item.getLastdate())));                        Element flag = document.createElement("flag");            flag.appendChild(document.createTextNode(String.valueOf(item.getFlag())));                        admin.appendChild(rid);            admin.appendChild(type);            admin.appendChild(lastdate);            admin.appendChild(flag);                        root.appendChild(admin);        }                document.appendChild(root);                                return document;    }

然後將該記憶體的XML儲存到本地中:

    public static void main(String[] args) throws Exception    {        List<Admin> allAdmins  = loadFromDB();        Document document = getDocument(allAdmins);                Source source = new DOMSource(document);        StreamResult stream = new StreamResult(new FileOutputStream(new File("C:\\D\\code\\resource\\admins.xml")));        TransformerFactory transFactory = TransformerFactory.newInstance();        Transformer trans = transFactory.newTransformer();        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");        trans.transform(source, stream);                System.out.println("main done//~~");    }

 

Java產生XML檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.