当前位置 : 主页 > 编程语言 > c++ >

用Java将数据写入XML文件

来源:互联网 收集:自由互联 发布时间:2021-07-03
Java功能片段 package org.jxnd.test;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.ut
Java功能片段
package org.jxnd.test;

import java.io.File;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.jxnd.bean.Roles;
import org.jxnd.bean.UserInfo;
import org.xml.sax.DocumentHandler;

public class Test {
    public static void main(String[] args) throws DocumentException, IOException {
    	List
 
   list=new ArrayList
  
   (); list.add(new UserInfo(1001,"大东","123456",1,new Roles(1,"CEO"))); list.add(new UserInfo(1002,"苍老师","123",2,new Roles(2,"BOSS"))); list.add(new UserInfo(1003,"万牛逼","1234",3,new Roles(3,"CTO"))); Element root=DocumentHelper.createElement("students"); Document doc=DocumentHelper.createDocument(root); for(UserInfo info:list){ Element student=DocumentHelper.createElement("student"); Element id=DocumentHelper.createElement("id"); id.setText(info.getId()+""); Element name=DocumentHelper.createElement("name"); name.setText(info.getName()); Element pwd=DocumentHelper.createElement("pwd"); pwd.setText(info.getPwd()); Element roleid=DocumentHelper.createElement("rolesid"); roleid.setText(info.getRolesid()+""); Element rinfo=DocumentHelper.createElement("rinfo"); Element rid=DocumentHelper.createElement("rid"); rid.setText(info.getRinfo().getId()+""); Element rname=DocumentHelper.createElement("rname"); rname.setText(info.getRinfo().getName()); rinfo.add(rid); rinfo.add(rname); student.add(id); student.add(name); student.add(pwd); student.add(roleid); student.add(rinfo); student.addAttribute("class", info.getId()+""); root.add(student); FileOutputStream out=new FileOutputStream("student.xml"); OutputFormat format=new OutputFormat(" ", true); XMLWriter writer=new XMLWriter(out,format); writer.write(doc); out.close(); writer.close(); } } }
  
 
XML文件信息
 


 
  
   
   
    1001
    
   
    大东
    
   
    123456
    
   
    1
    
    
    
     1
     
    
     CEO
     
    
  
  
   
   
    1002
    
   
    苍老师
    
   
    123
    
   
    2
    
    
    
     2
     
    
     BOSS
     
    
  
  
   
   
    1003
    
   
    万牛逼
    
   
    1234
    
   
    3
    
    
    
     3
     
    
     CTO
     
    
  

 
网友评论