java轉換CSV文件生成xml格式數據


注冊CSDN快六個月了,之前一直是看園子里的文章,或者碰到問題時,進來查點資料,今天終於決定寫一篇自己在園子里的blog。

好吧,鑒於水平太菜,就只記錄過程,其中原理啥的並不是很明晰,所以此blog只在記錄,莫BS哈。

神馬是CSV文件呢,看起來和excel文件很像,具體有神馬不同,見這位圓友的blog哈,http://blog.csdn.net/luweifeng1983/article/details/3582657 。簡單來說,本質是文本文件,但文件分多行,內容以“,”分割,系統默認是excel打開的一種文件。

好吧,我們以下面這個通訊錄CSV文件為例。

name company mobile-phone address relationship
Lisa hp 18702341678 Wuhan classmates
Tony ibm 15809323145 Wuhan friends

下面開始轉換過程的講解嘍。

1. 讀取csv文件

1)Java操作csv文件有專門的的API叫javacsv.jar

下載地址如下:

http://sourceforge.net/project/showfiles.php?group_id=33066

2)自己項目中使用的工具是dataimport_3.3.0-rc1.jar

下載地址如下:

http://grepcode.com/snapshot/repo1.maven.org/maven2/net.sf.squirrel-sql.plugins/dataimport/3.3.0-rc1

讀取示例代碼:

            //read csv file
            CsvReader cr = new CsvReader(new InputStreamReader(new FileInputStream(new File(filename)),
                                                              "UTF-8"));
            //read csv file headers
            cr.readHeaders();
           
            //read csvv file records

           cr.readRecord();

2.將讀取到的csv文件轉換成xml格式

1)先確定自己要求替換完的xml數據的格式,假如如下圖定義,可設置為資源文件,命名為addresslist.xml.

<?xml version="1.0" encoding="UTF-8"?>
<AddressList>
 <Person>
  <Name>@name@</Name>
  <Company>@company@</Company>
  <MobilePhone>@mobilephone@</MobilePhone>
  <Address>@address@</Address>
  <Relationship>@relationship@</Relationship>
    </Person>
</AddressList>

2)讀取資源文件addresslist.xml。

            String mapping = "addresslist.xml";

            URL url = ConfigurationUtils.locate(mapping);
            SAXReader reader = new SAXReader();
            Document doc = reader.read(url);

3)完成替換(此步驟是將CSV文件中的數據記錄按行替換資源文件中的占位符,生成xml消息)

//find Node "Name" in addresslist.xml
Element name = (Element) doc.selectSingleNode("/AddressList/Person/Name");
//read "name" from csv file and set value for Node "Name"
name.setText(cr.get("name"));
//find Node "Company" in addresslist.xml
Element company = (Element) doc.selectSingleNode("/AddressList/Person/Company");
//read "company" from csv file and set value for Node "Company"
company.setText(cr.get("company");
//find Node "MobilePhone" in addresslist.xml
Element mobilephone = (Element) doc.selectSingleNode("/AddressList/Person/MobilePhone");
//read "mobile-phone" from csv file and set value for Node "MobilePhone"
mobilephone.setText(cr.get("mobile-phone"));
//find Node "Address" in addresslist.xml
Element address = (Element) doc.selectSingleNode("/AddressList/Person/Address");
//read "address" from csv file and set value for Node "Address"
mobilephone.setText(cr.get("address"));
//find Node "RelationShip" in addresslist.xml
Element relationship = (Element) doc.selectSingleNode("/AddressList/Person/RelationShip");
//read "relationship" from csv file and set value for Node "RelationShip"
relationship.setText(cr.get("relationship"));

4)將xml消息轉換成文本輸出

String record= doc.asXML();

可配合while,循環轉換csv文件中的三條記錄。

完整的java code來了呢

 

 1 package demo.csv;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileNotFoundException;
 6 import java.io.IOException;
 7 import java.io.InputStreamReader;
 8 import java.io.UnsupportedEncodingException;
 9 import java.net.URL;
10 import java.util.ArrayList;
11 import java.util.Iterator;
12 import java.util.List;
13 
14 import org.apache.commons.configuration.ConfigurationUtils;
15 import org.dom4j.Document;
16 import org.dom4j.Element;
17 import org.dom4j.io.SAXReader;
18 
19 import com.csvreader.CsvReader;
20 
21 public class CsvDemo {
22     
23     private static List<String> transformCsv2Xml(String filename) {
24 
25         String mapping = "src/demo/csv/address.xml";
26 
27         List<String> messages = new ArrayList<String>();
28 
29         try {
30             URL url = ConfigurationUtils.locate(mapping);
31             SAXReader reader = new SAXReader();
32             Document doc = reader.read(url);
33 
34             //read csv file
35             CsvReader cr = new CsvReader(new InputStreamReader(new FileInputStream(new File(filename)), 
36                                                               "UTF-8"));
37             //read csv file headers 
38             cr.readHeaders();
39             
40             //read csv file records
41             //cr.readRecord();
42             while (cr.readRecord()) {
43                 //find Node "Name" in addresslist.xml
44                 Element name = (Element) doc.selectSingleNode("/AddressList/Person/Name");
45                 //read "name" from csv file and set value for Node "Name"
46                 name.setText(cr.get("name").trim());
47                 //find Node "Company" in addresslist.xml
48                 Element company = (Element) doc.selectSingleNode("/AddressList/Person/Company");
49                 //read "company" from csv file and set value for Node "Company"
50                 company.setText(cr.get("company").trim());
51                 //find Node "MobilePhone" in addresslist.xml
52                 Element mobilephone = (Element) doc.selectSingleNode("/AddressList/Person/MobilePhone");
53                 //read "mobile-phone" from csv file and set value for Node "MobilePhone"
54                 mobilephone.setText(cr.get("mobile-phone").trim());
55                 //find Node "Address" in addresslist.xml
56                 Element address = (Element) doc.selectSingleNode("/AddressList/Person/Address");
57                 //read "address" from csv file and set value for Node "Address"
58                 address.setText(cr.get("address").trim());
59                 //find Node "RelationShip" in addresslist.xml
60                 Element relationship = (Element) doc.selectSingleNode("/AddressList/Person/Relationship");
61                 //read "relationship" from csv file and set value for Node "RelationShip"
62                 relationship.setText(cr.get("relationship").trim());
63                 // break;
64                  messages.add(doc.asXML());
65             }
66            
67         } catch (UnsupportedEncodingException e) {
68 
69         } catch (FileNotFoundException e) {
70 
71         } catch (IOException e) {
72 
73         } catch (Exception ex) {
74 
75         }
76         return messages;
77     }
78 
79 
80     public static void main(String[] args) {
81         
82         List<String> addresslist = transformCsv2Xml("src/demo/csv/data.csv");
83         Iterator<String> it = addresslist.iterator();
84         while(it.hasNext()){
85             System.out.println(it.next());
86         }
87 
88     }
89 
90 }
View Code

 

 

介紹完畢,,,雖然內容很少,但完整記錄下來好費時間,可能是太菜,思路也不太清楚的原因吧,好吧,還是累屎姐了,不知道下一次下決心寫會是神馬時候。

                                                                                                                                                                                       2013-05-14

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM