Is there an existing application or library in Java which will allow me to convert a CSV
data file to XML
file?
Java中是否存在一个现有的应用程序或库,允许我将CSV数据文件转换为XML文件?
The XML
tags would be provided through possibly the first row containing column headings.
XML标记可能通过包含列标题的第一行提供。
16 个解决方案
#1
60
Maybe this might help: JSefa
也许这能帮上忙:JSefa
You can read CSV file with this tool and serialize it to XML.
您可以使用此工具读取CSV文件并将其序列化为XML。
#2
45
As the others above, I don't know any one-step way to do that, but if you are ready to use very simple external libraries, I would suggest:
正如上面提到的其他方法一样,我不知道任何一种方法可以做到这一点,但是如果您准备使用非常简单的外部库,我建议:
OpenCsv for parsing CSV (small, simple, reliable and easy to use)
用于解析CSV的OpenCsv(小、简单、可靠且易于使用)
Xstream to parse/serialize XML (very very easy to use, and creating fully human readable xml)
Xstream解析/序列化XML(非常容易使用,并创建完全人类可读的XML)
Using the same sample data as above, code would look like:
使用与上面相同的示例数据,代码如下:
package fr.megiste.test;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import au.com.bytecode.opencsv.CSVReader;
import com.thoughtworks.xstream.XStream;
public class CsvToXml {
public static void main(String[] args) {
String startFile = "./startData.csv";
String outFile = "./outData.xml";
try {
CSVReader reader = new CSVReader(new FileReader(startFile));
String[] line = null;
String[] header = reader.readNext();
List out = new ArrayList();
while((line = reader.readNext())!=null){
List<String[]> item = new ArrayList<String[]>();
for (int i = 0; i < header.length; i++) {
String[] keyVal = new String[2];
String string = header[i];
String val = line[i];
keyVal[0] = string;
keyVal[1] = val;
item.add(keyVal);
}
out.add(item);
}
XStream xstream = new XStream();
xstream.toXML(out, new FileWriter(outFile,false));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Producing the following result: (Xstream allows very fine tuning of the result...)
产生以下结果:(Xstream允许对结果进行非常精细的调优…)
<list>
<list>
<string-array>
<string>string</string>
<string>hello world</string>
</string-array>
<string-array>
<string>float1</string>
<string>1.0</string>
</string-array>
<string-array>
<string>float2</string>
<string>3.3</string>
</string-array>
<string-array>
<string>integer</string>
<string>4</string>
</string-array>
</list>
<list>
<string-array>
<string>string</string>
<string>goodbye world</string>
</string-array>
<string-array>
<string>float1</string>
<string>1e9</string>
</string-array>
<string-array>
<string>float2</string>
<string>-3.3</string>
</string-array>
<string-array>
<string>integer</string>
<string>45</string>
</string-array>
</list>
<list>
<string-array>
<string>string</string>
<string>hello again</string>
</string-array>
<string-array>
<string>float1</string>
<string>-1</string>
</string-array>
<string-array>
<string>float2</string>
<string>23.33</string>
</string-array>
<string-array>
<string>integer</string>
<string>456</string>
</string-array>
</list>
<list>
<string-array>
<string>string</string>
<string>hello world 3</string>
</string-array>
<string-array>
<string>float1</string>
<string>1.40</string>
</string-array>
<string-array>
<string>float2</string>
<string>34.83</string>
</string-array>
<string-array>
<string>integer</string>
<string>4999</string>
</string-array>
</list>
<list>
<string-array>
<string>string</string>
<string>hello 2 world</string>
</string-array>
<string-array>
<string>float1</string>
<string>9981.05</string>
</string-array>
<string-array>
<string>float2</string>
<string>43.33</string>
</string-array>
<string-array>
<string>integer</string>
<string>444</string>
</string-array>
</list>
</list>
#3
24
I know you asked for Java, but this strikes me as a task well suited to a scripting language. Here is a quick (very simple) solution written in Groovy.
我知道您需要Java,但我认为这是一项非常适合脚本语言的任务。这里有一个用Groovy编写的快速(非常简单)的解决方案。
test.csv
test.csv
string,float1,float2,integer
hello world,1.0,3.3,4
goodbye world,1e9,-3.3,45
hello again,-1,23.33,456
hello world 3,1.40,34.83,4999
hello 2 world,9981.05,43.33,444
csvtoxml.groovy
csvtoxml.groovy
#!/usr/bin/env groovy
def csvdata = []
new File("test.csv").eachLine { line ->
csvdata << line.split(',')
}
def headers = csvdata[0]
def dataRows = csvdata[1..-1]
def xml = new groovy.xml.MarkupBuilder()
// write 'root' element
xml.root {
dataRows.eachWithIndex { dataRow, index ->
// write 'entry' element with 'id' attribute
entry(id:index+1) {
headers.eachWithIndex { heading, i ->
// write each heading with associated content
"${heading}"(dataRow[i])
}
}
}
}
Writes the following XML to stdout:
将以下XML写入stdout:
<root>
<entry id='1'>
<string>hello world</string>
<float1>1.0</float1>
<float2>3.3</float2>
<integer>4</integer>
</entry>
<entry id='2'>
<string>goodbye world</string>
<float1>1e9</float1>
<float2>-3.3</float2>
<integer>45</integer>
</entry>
<entry id='3'>
<string>hello again</string>
<float1>-1</float1>
<float2>23.33</float2>
<integer>456</integer>
</entry>
<entry id='4'>
<string>hello world 3</string>
<float1>1.40</float1>
<float2>34.83</float2>
<integer>4999</integer>
</entry>
<entry id='5'>
<string>hello 2 world</string>
<float1>9981.05</float1>
<float2>43.33</float2>
<integer>444</integer>
</entry>
</root>
However, the code does very simple parsing (not taking into account quoted or escaped commas) and it does not account for possible absent data.
但是,代码执行非常简单的解析(不考虑引用或转义的逗号),并且不考虑可能的缺席数据。
#4
17
I have an opensource framework for working with CSV and flat files in general. Maybe it's worth looking: JFileHelpers.
我有一个opensource框架来处理CSV和平面文件。也许它值得一看:jfilehelper函数。
With that toolkit you can write code using beans, like:
使用该工具包,您可以使用bean编写代码,比如:
@FixedLengthRecord()
public class Customer {
@FieldFixedLength(4)
public Integer custId;
@FieldAlign(alignMode=AlignMode.Right)
@FieldFixedLength(20)
public String name;
@FieldFixedLength(3)
public Integer rating;
@FieldTrim(trimMode=TrimMode.Right)
@FieldFixedLength(10)
@FieldConverter(converter = ConverterKind.Date,
format = "dd-MM-yyyy")
public Date addedDate;
@FieldFixedLength(3)
@FieldOptional
public String stockSimbol;
}
and then just parse your text files using:
然后用以下方法解析文本文件:
FileHelperEngine<Customer> engine =
new FileHelperEngine<Customer>(Customer.class);
List<Customer> customers =
new ArrayList<Customer>();
customers = engine.readResource(
"/samples/customers-fixed.txt");
And you'll have a collection of parsed objects.
您将拥有解析对象的集合。
Hope that helps!
希望会有帮助!
#5
15
This solution does not need any CSV or XML libraries and, I know, it does not handle any illegal characters and encoding issues, but you might be interested in it as well, provided your CSV input does not break the above mentioned rules.
这个解决方案不需要任何CSV或XML库,而且我知道,它不处理任何非法字符和编码问题,但是您也可能对它感兴趣,前提是您的CSV输入不违反上述规则。
Attention: You should not use this code unless you know what you do or don't have the chance to use a further library (possible in some bureaucratic projects)... Use a StringBuffer for older Runtime Environments...
注意:除非您知道自己在做什么或者没有机会使用进一步的库(在一些官僚项目中可能),否则不应该使用此代码。为旧的运行时环境使用StringBuffer……
So here we go:
所以我们开始吧:
BufferedReader reader = new BufferedReader(new InputStreamReader(
Csv2Xml.class.getResourceAsStream("test.csv")));
StringBuilder xml = new StringBuilder();
String lineBreak = System.getProperty("line.separator");
String line = null;
List<String> headers = new ArrayList<String>();
boolean isHeader = true;
int count = 0;
int entryCount = 1;
xml.append("<root>");
xml.append(lineBreak);
while ((line = reader.readLine()) != null) {
StringTokenizer tokenizer = new StringTokenizer(line, ",");
if (isHeader) {
isHeader = false;
while (tokenizer.hasMoreTokens()) {
headers.add(tokenizer.nextToken());
}
} else {
count = 0;
xml.append("\t<entry id=\"");
xml.append(entryCount);
xml.append("\">");
xml.append(lineBreak);
while (tokenizer.hasMoreTokens()) {
xml.append("\t\t<");
xml.append(headers.get(count));
xml.append(">");
xml.append(tokenizer.nextToken());
xml.append("</");
xml.append(headers.get(count));
xml.append(">");
xml.append(lineBreak);
count++;
}
xml.append("\t</entry>");
xml.append(lineBreak);
entryCount++;
}
}
xml.append("</root>");
System.out.println(xml.toString());
The input test.csv (stolen from another answer on this page):
输入测试。csv(从本页的另一个答案中窃取):
string,float1,float2,integer
hello world,1.0,3.3,4
goodbye world,1e9,-3.3,45
hello again,-1,23.33,456
hello world 3,1.40,34.83,4999
hello 2 world,9981.05,43.33,444
The resulting output:
结果输出:
<root>
<entry id="1">
<string>hello world</string>
<float1>1.0</float1>
<float2>3.3</float2>
<integer>4</integer>
</entry>
<entry id="2">
<string>goodbye world</string>
<float1>1e9</float1>
<float2>-3.3</float2>
<integer>45</integer>
</entry>
<entry id="3">
<string>hello again</string>
<float1>-1</float1>
<float2>23.33</float2>
<integer>456</integer>
</entry>
<entry id="4">
<string>hello world 3</string>
<float1>1.40</float1>
<float2>34.83</float2>
<integer>4999</integer>
</entry>
<entry id="5">
<string>hello 2 world</string>
<float1>9981.05</float1>
<float2>43.33</float2>
<integer>444</integer>
</entry>
</root>
#6
14
The big difference is that JSefa brings in is that it can serialize your java objects to CSV/XML/etc files and can deserialize back to java objects. And it's driven by annotations which gives you lot of control over the output.
JSefa带来的最大区别是,它可以将java对象序列化为CSV/XML/etc文件,并可以反序列化回java对象。它是由注解驱动的注解给你对输出的控制。
JFileHelpers also looks interesting.
JFileHelpers看起来也很有趣。
#7
14
You can do this exceptionally easily using Groovy, and the code is very readable.
您可以非常轻松地使用Groovy实现这一点,而且代码非常易读。
Basically, the text variable will be written to contacts.xml
for each line in the contactData.csv
, and the fields array contains each column.
基本上,文本变量将被写入联系人。用于contactData中的每一行的xml。csv和字段数组包含每个列。
def file1 = new File('c:\\temp\\ContactData.csv')
def file2 = new File('c:\\temp\\contacts.xml')
def reader = new FileReader(file1)
def writer = new FileWriter(file2)
reader.transformLine(writer) { line ->
fields = line.split(',')
text = """<CLIENTS>
<firstname> ${fields[2]} </firstname>
<surname> ${fields[1]} </surname>
<email> ${fields[9]} </email>
<employeenumber> password </employeenumber>
<title> ${fields[4]} </title>
<phone> ${fields[3]} </phone>
</CLIENTS>"""
}
#8
13
I don't understand why you would want to do this. It sounds almost like cargo cult coding.
我不明白你为什么要这么做。这听起来几乎像货物崇拜编码。
Converting a CSV file to XML doesn't add any value. Your program is already reading the CSV file, so arguing that you need XML doesn't work.
将CSV文件转换为XML不会增加任何价值。您的程序已经在读取CSV文件,因此争论说您需要XML不能工作。
On the other hand, reading the CSV file, doing something with the values, and then serializing to XML does make sense (well, as much as using XML can make sense... ;)) but you would supposedly already have a means of serializing to XML.
另一方面,读取CSV文件,用这些值做一些事情,然后序列化到XML确实是有意义的(当然,使用XML是有意义的……)但是您应该已经有了一种序列化XML的方法。
#9
11
You could use XSLT. Google it and you will find a few examples e.g. CSV to XML If you use XSLT you can then convert the XML to whatever format you want.
您可以使用XSLT。谷歌,你会发现一些例子,比如CSV到XML如果你使用XSLT,你可以将XML转换成你想要的格式。
#10
8
There is also good library ServingXML by Daniel Parker, which is able to convert almost any plain text format to XML and back.
丹尼尔•帕克(Daniel Parker)的优秀库ServingXML也能将几乎所有纯文本格式转换为XML并返回。
The example for your case can be found here: It uses heading of field in CSV file as the XML element name.
您的示例可以在这里找到:它使用CSV文件中的字段标题作为XML元素名称。
#11
7
There is nothing I know of that can do this without you at least writing a little bit of code... You will need 2 separate library:
我所知道的没有任何东西可以做到这一点,除非你至少写一点代码……你需要两个独立的图书馆:
- A CSV Parser Framework
- 一个CSV解析器框架
- An XML Serialization Framework
- 一个XML序列化框架
The CSV parser I would recommend (unless you want to have a little bit of fun to write your own CSV Parser) is OpenCSV (A SourceForge Project for parsing CSV Data)
我推荐的CSV解析器是OpenCSV(用于解析CSV数据的SourceForge项目)
The XML Serialization Framework should be something that can scale in case you want to transform large (or huge) CSV file to XML: My recommendation is the Sun Java Streaming XML Parser Framework (See here) which allows pull-parsing AND serialization.
如果您想要将大型(或大型)CSV文件转换为XML,那么XML序列化框架应该是可以伸缩的:我的建议是使用Sun Java流XML解析器框架(参见这里),它允许拖放解析和序列化。
#12
7
As far as I know, there's no ready-made library to do this for you, but producing a tool capable of translating from CSV to XML should only require you to write a crude CSV parser and hook up JDOM (or your XML Java library of choice) with some glue code.
据我所知,还没有现成的库来为您实现这一点,但是生成一个能够从CSV转换到XML的工具应该只需要编写一个粗略的CSV解析器,并将JDOM(或者您选择的XML Java库)与一些胶水代码连接起来。
#13
4
Jackson processor family has backends for multiple data formats, not just JSON. This includes both XML (https://github.com/FasterXML/jackson-dataformat-xml) and CSV (https://github.com/FasterXML/jackson-dataformat-csv/) backends.
Jackson处理器系列支持多种数据格式,而不仅仅是JSON。这包括XML (https://github.com/FasterXML/jackson-dataformat-xml)和CSV (https://github.com/FasterXML/jackson-dataformat-csv/)。
Conversion would rely on reading input with CSV backend, write using XML backend. This is easiest to do if you have (or can define) a POJO for per-row (CSV) entries. This is not a strict requirement, as content from CSV may be read "untyped" as well (a sequence of String
arrays), but requires bit more work on XML output.
转换将依赖于使用CSV后端读取输入、使用XML后端写入。如果您有(或可以定义)针对每行(CSV)条目的POJO,这是最容易做到的。这并不是一个严格的要求,因为CSV中的内容也可以被读取为“非类型化的”(字符串数组的序列),但是需要在XML输出上做更多的工作。
For XML side, you would need a wrapper root object to contain array or List
of objects to serialize.
对于XML方面,需要一个包装器根对象来包含要序列化的数组或对象列表。
#14
3
This may be too basic or limited of a solution, but couldn't you do a String.split()
on each line of the file, remembering the result array of the first line to generate the XML, and just spit each line's array data out with the proper XML elements padding each iteration of a loop?
这可能是太简单了还是有限的一个解决方案,但你不能做String.split()文件的每一行,记住第一行的结果数组生成XML,就吐每一行与适当的XML元素的数组数据填充循环的每次迭代?
#15
3
I had the same problem and needed an application to convert a CSV file to a XML file for one of my projects, but didn't find anything free and good enough on the net, so I coded my own Java Swing CSVtoXML application.
我遇到了同样的问题,需要一个应用程序来为我的一个项目将CSV文件转换为XML文件,但是在网上找不到任何免费的、足够好的东西,所以我编写了自己的Java Swing CSVtoXML应用程序。
It's available from my website HERE. Hope it will help you.
可以在我的网站上找到。希望它能对你有所帮助。
If not, you can easily code your own like I did; The source code is inside the jar file so modify it as you need if it doesn't fill your requirement.
如果没有,你可以很容易地编写自己的代码;源代码在jar文件中,因此如果不满足您的需求,可以根据需要修改它。
#1
60
Maybe this might help: JSefa
也许这能帮上忙:JSefa
You can read CSV file with this tool and serialize it to XML.
您可以使用此工具读取CSV文件并将其序列化为XML。
#2
45
As the others above, I don't know any one-step way to do that, but if you are ready to use very simple external libraries, I would suggest:
正如上面提到的其他方法一样,我不知道任何一种方法可以做到这一点,但是如果您准备使用非常简单的外部库,我建议:
OpenCsv for parsing CSV (small, simple, reliable and easy to use)
用于解析CSV的OpenCsv(小、简单、可靠且易于使用)
Xstream to parse/serialize XML (very very easy to use, and creating fully human readable xml)
Xstream解析/序列化XML(非常容易使用,并创建完全人类可读的XML)
Using the same sample data as above, code would look like:
使用与上面相同的示例数据,代码如下:
package fr.megiste.test;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import au.com.bytecode.opencsv.CSVReader;
import com.thoughtworks.xstream.XStream;
public class CsvToXml {
public static void main(String[] args) {
String startFile = "./startData.csv";
String outFile = "./outData.xml";
try {
CSVReader reader = new CSVReader(new FileReader(startFile));
String[] line = null;
String[] header = reader.readNext();
List out = new ArrayList();
while((line = reader.readNext())!=null){
List<String[]> item = new ArrayList<String[]>();
for (int i = 0; i < header.length; i++) {
String[] keyVal = new String[2];
String string = header[i];
String val = line[i];
keyVal[0] = string;
keyVal[1] = val;
item.add(keyVal);
}
out.add(item);
}
XStream xstream = new XStream();
xstream.toXML(out, new FileWriter(outFile,false));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Producing the following result: (Xstream allows very fine tuning of the result...)
产生以下结果:(Xstream允许对结果进行非常精细的调优…)
<list>
<list>
<string-array>
<string>string</string>
<string>hello world</string>
</string-array>
<string-array>
<string>float1</string>
<string>1.0</string>
</string-array>
<string-array>
<string>float2</string>
<string>3.3</string>
</string-array>
<string-array>
<string>integer</string>
<string>4</string>
</string-array>
</list>
<list>
<string-array>
<string>string</string>
<string>goodbye world</string>
</string-array>
<string-array>
<string>float1</string>
<string>1e9</string>
</string-array>
<string-array>
<string>float2</string>
<string>-3.3</string>
</string-array>
<string-array>
<string>integer</string>
<string>45</string>
</string-array>
</list>
<list>
<string-array>
<string>string</string>
<string>hello again</string>
</string-array>
<string-array>
<string>float1</string>
<string>-1</string>
</string-array>
<string-array>
<string>float2</string>
<string>23.33</string>
</string-array>
<string-array>
<string>integer</string>
<string>456</string>
</string-array>
</list>
<list>
<string-array>
<string>string</string>
<string>hello world 3</string>
</string-array>
<string-array>
<string>float1</string>
<string>1.40</string>
</string-array>
<string-array>
<string>float2</string>
<string>34.83</string>
</string-array>
<string-array>
<string>integer</string>
<string>4999</string>
</string-array>
</list>
<list>
<string-array>
<string>string</string>
<string>hello 2 world</string>
</string-array>
<string-array>
<string>float1</string>
<string>9981.05</string>
</string-array>
<string-array>
<string>float2</string>
<string>43.33</string>
</string-array>
<string-array>
<string>integer</string>
<string>444</string>
</string-array>
</list>
</list>
#3
24
I know you asked for Java, but this strikes me as a task well suited to a scripting language. Here is a quick (very simple) solution written in Groovy.
我知道您需要Java,但我认为这是一项非常适合脚本语言的任务。这里有一个用Groovy编写的快速(非常简单)的解决方案。
test.csv
test.csv
string,float1,float2,integer
hello world,1.0,3.3,4
goodbye world,1e9,-3.3,45
hello again,-1,23.33,456
hello world 3,1.40,34.83,4999
hello 2 world,9981.05,43.33,444
csvtoxml.groovy
csvtoxml.groovy
#!/usr/bin/env groovy
def csvdata = []
new File("test.csv").eachLine { line ->
csvdata << line.split(',')
}
def headers = csvdata[0]
def dataRows = csvdata[1..-1]
def xml = new groovy.xml.MarkupBuilder()
// write 'root' element
xml.root {
dataRows.eachWithIndex { dataRow, index ->
// write 'entry' element with 'id' attribute
entry(id:index+1) {
headers.eachWithIndex { heading, i ->
// write each heading with associated content
"${heading}"(dataRow[i])
}
}
}
}
Writes the following XML to stdout:
将以下XML写入stdout:
<root>
<entry id='1'>
<string>hello world</string>
<float1>1.0</float1>
<float2>3.3</float2>
<integer>4</integer>
</entry>
<entry id='2'>
<string>goodbye world</string>
<float1>1e9</float1>
<float2>-3.3</float2>
<integer>45</integer>
</entry>
<entry id='3'>
<string>hello again</string>
<float1>-1</float1>
<float2>23.33</float2>
<integer>456</integer>
</entry>
<entry id='4'>
<string>hello world 3</string>
<float1>1.40</float1>
<float2>34.83</float2>
<integer>4999</integer>
</entry>
<entry id='5'>
<string>hello 2 world</string>
<float1>9981.05</float1>
<float2>43.33</float2>
<integer>444</integer>
</entry>
</root>
However, the code does very simple parsing (not taking into account quoted or escaped commas) and it does not account for possible absent data.
但是,代码执行非常简单的解析(不考虑引用或转义的逗号),并且不考虑可能的缺席数据。
#4
17
I have an opensource framework for working with CSV and flat files in general. Maybe it's worth looking: JFileHelpers.
我有一个opensource框架来处理CSV和平面文件。也许它值得一看:jfilehelper函数。
With that toolkit you can write code using beans, like:
使用该工具包,您可以使用bean编写代码,比如:
@FixedLengthRecord()
public class Customer {
@FieldFixedLength(4)
public Integer custId;
@FieldAlign(alignMode=AlignMode.Right)
@FieldFixedLength(20)
public String name;
@FieldFixedLength(3)
public Integer rating;
@FieldTrim(trimMode=TrimMode.Right)
@FieldFixedLength(10)
@FieldConverter(converter = ConverterKind.Date,
format = "dd-MM-yyyy")
public Date addedDate;
@FieldFixedLength(3)
@FieldOptional
public String stockSimbol;
}
and then just parse your text files using:
然后用以下方法解析文本文件:
FileHelperEngine<Customer> engine =
new FileHelperEngine<Customer>(Customer.class);
List<Customer> customers =
new ArrayList<Customer>();
customers = engine.readResource(
"/samples/customers-fixed.txt");
And you'll have a collection of parsed objects.
您将拥有解析对象的集合。
Hope that helps!
希望会有帮助!
#5
15
This solution does not need any CSV or XML libraries and, I know, it does not handle any illegal characters and encoding issues, but you might be interested in it as well, provided your CSV input does not break the above mentioned rules.
这个解决方案不需要任何CSV或XML库,而且我知道,它不处理任何非法字符和编码问题,但是您也可能对它感兴趣,前提是您的CSV输入不违反上述规则。
Attention: You should not use this code unless you know what you do or don't have the chance to use a further library (possible in some bureaucratic projects)... Use a StringBuffer for older Runtime Environments...
注意:除非您知道自己在做什么或者没有机会使用进一步的库(在一些官僚项目中可能),否则不应该使用此代码。为旧的运行时环境使用StringBuffer……
So here we go:
所以我们开始吧:
BufferedReader reader = new BufferedReader(new InputStreamReader(
Csv2Xml.class.getResourceAsStream("test.csv")));
StringBuilder xml = new StringBuilder();
String lineBreak = System.getProperty("line.separator");
String line = null;
List<String> headers = new ArrayList<String>();
boolean isHeader = true;
int count = 0;
int entryCount = 1;
xml.append("<root>");
xml.append(lineBreak);
while ((line = reader.readLine()) != null) {
StringTokenizer tokenizer = new StringTokenizer(line, ",");
if (isHeader) {
isHeader = false;
while (tokenizer.hasMoreTokens()) {
headers.add(tokenizer.nextToken());
}
} else {
count = 0;
xml.append("\t<entry id=\"");
xml.append(entryCount);
xml.append("\">");
xml.append(lineBreak);
while (tokenizer.hasMoreTokens()) {
xml.append("\t\t<");
xml.append(headers.get(count));
xml.append(">");
xml.append(tokenizer.nextToken());
xml.append("</");
xml.append(headers.get(count));
xml.append(">");
xml.append(lineBreak);
count++;
}
xml.append("\t</entry>");
xml.append(lineBreak);
entryCount++;
}
}
xml.append("</root>");
System.out.println(xml.toString());
The input test.csv (stolen from another answer on this page):
输入测试。csv(从本页的另一个答案中窃取):
string,float1,float2,integer
hello world,1.0,3.3,4
goodbye world,1e9,-3.3,45
hello again,-1,23.33,456
hello world 3,1.40,34.83,4999
hello 2 world,9981.05,43.33,444
The resulting output:
结果输出:
<root>
<entry id="1">
<string>hello world</string>
<float1>1.0</float1>
<float2>3.3</float2>
<integer>4</integer>
</entry>
<entry id="2">
<string>goodbye world</string>
<float1>1e9</float1>
<float2>-3.3</float2>
<integer>45</integer>
</entry>
<entry id="3">
<string>hello again</string>
<float1>-1</float1>
<float2>23.33</float2>
<integer>456</integer>
</entry>
<entry id="4">
<string>hello world 3</string>
<float1>1.40</float1>
<float2>34.83</float2>
<integer>4999</integer>
</entry>
<entry id="5">
<string>hello 2 world</string>
<float1>9981.05</float1>
<float2>43.33</float2>
<integer>444</integer>
</entry>
</root>
#6
14
The big difference is that JSefa brings in is that it can serialize your java objects to CSV/XML/etc files and can deserialize back to java objects. And it's driven by annotations which gives you lot of control over the output.
JSefa带来的最大区别是,它可以将java对象序列化为CSV/XML/etc文件,并可以反序列化回java对象。它是由注解驱动的注解给你对输出的控制。
JFileHelpers also looks interesting.
JFileHelpers看起来也很有趣。
#7
14
You can do this exceptionally easily using Groovy, and the code is very readable.
您可以非常轻松地使用Groovy实现这一点,而且代码非常易读。
Basically, the text variable will be written to contacts.xml
for each line in the contactData.csv
, and the fields array contains each column.
基本上,文本变量将被写入联系人。用于contactData中的每一行的xml。csv和字段数组包含每个列。
def file1 = new File('c:\\temp\\ContactData.csv')
def file2 = new File('c:\\temp\\contacts.xml')
def reader = new FileReader(file1)
def writer = new FileWriter(file2)
reader.transformLine(writer) { line ->
fields = line.split(',')
text = """<CLIENTS>
<firstname> ${fields[2]} </firstname>
<surname> ${fields[1]} </surname>
<email> ${fields[9]} </email>
<employeenumber> password </employeenumber>
<title> ${fields[4]} </title>
<phone> ${fields[3]} </phone>
</CLIENTS>"""
}
#8
13
I don't understand why you would want to do this. It sounds almost like cargo cult coding.
我不明白你为什么要这么做。这听起来几乎像货物崇拜编码。
Converting a CSV file to XML doesn't add any value. Your program is already reading the CSV file, so arguing that you need XML doesn't work.
将CSV文件转换为XML不会增加任何价值。您的程序已经在读取CSV文件,因此争论说您需要XML不能工作。
On the other hand, reading the CSV file, doing something with the values, and then serializing to XML does make sense (well, as much as using XML can make sense... ;)) but you would supposedly already have a means of serializing to XML.
另一方面,读取CSV文件,用这些值做一些事情,然后序列化到XML确实是有意义的(当然,使用XML是有意义的……)但是您应该已经有了一种序列化XML的方法。
#9
11
You could use XSLT. Google it and you will find a few examples e.g. CSV to XML If you use XSLT you can then convert the XML to whatever format you want.
您可以使用XSLT。谷歌,你会发现一些例子,比如CSV到XML如果你使用XSLT,你可以将XML转换成你想要的格式。
#10
8
There is also good library ServingXML by Daniel Parker, which is able to convert almost any plain text format to XML and back.
丹尼尔•帕克(Daniel Parker)的优秀库ServingXML也能将几乎所有纯文本格式转换为XML并返回。
The example for your case can be found here: It uses heading of field in CSV file as the XML element name.
您的示例可以在这里找到:它使用CSV文件中的字段标题作为XML元素名称。
#11
7
There is nothing I know of that can do this without you at least writing a little bit of code... You will need 2 separate library:
我所知道的没有任何东西可以做到这一点,除非你至少写一点代码……你需要两个独立的图书馆:
- A CSV Parser Framework
- 一个CSV解析器框架
- An XML Serialization Framework
- 一个XML序列化框架
The CSV parser I would recommend (unless you want to have a little bit of fun to write your own CSV Parser) is OpenCSV (A SourceForge Project for parsing CSV Data)
我推荐的CSV解析器是OpenCSV(用于解析CSV数据的SourceForge项目)
The XML Serialization Framework should be something that can scale in case you want to transform large (or huge) CSV file to XML: My recommendation is the Sun Java Streaming XML Parser Framework (See here) which allows pull-parsing AND serialization.
如果您想要将大型(或大型)CSV文件转换为XML,那么XML序列化框架应该是可以伸缩的:我的建议是使用Sun Java流XML解析器框架(参见这里),它允许拖放解析和序列化。
#12
7
As far as I know, there's no ready-made library to do this for you, but producing a tool capable of translating from CSV to XML should only require you to write a crude CSV parser and hook up JDOM (or your XML Java library of choice) with some glue code.
据我所知,还没有现成的库来为您实现这一点,但是生成一个能够从CSV转换到XML的工具应该只需要编写一个粗略的CSV解析器,并将JDOM(或者您选择的XML Java库)与一些胶水代码连接起来。
#13
4
Jackson processor family has backends for multiple data formats, not just JSON. This includes both XML (https://github.com/FasterXML/jackson-dataformat-xml) and CSV (https://github.com/FasterXML/jackson-dataformat-csv/) backends.
Jackson处理器系列支持多种数据格式,而不仅仅是JSON。这包括XML (https://github.com/FasterXML/jackson-dataformat-xml)和CSV (https://github.com/FasterXML/jackson-dataformat-csv/)。
Conversion would rely on reading input with CSV backend, write using XML backend. This is easiest to do if you have (or can define) a POJO for per-row (CSV) entries. This is not a strict requirement, as content from CSV may be read "untyped" as well (a sequence of String
arrays), but requires bit more work on XML output.
转换将依赖于使用CSV后端读取输入、使用XML后端写入。如果您有(或可以定义)针对每行(CSV)条目的POJO,这是最容易做到的。这并不是一个严格的要求,因为CSV中的内容也可以被读取为“非类型化的”(字符串数组的序列),但是需要在XML输出上做更多的工作。
For XML side, you would need a wrapper root object to contain array or List
of objects to serialize.
对于XML方面,需要一个包装器根对象来包含要序列化的数组或对象列表。
#14
3
This may be too basic or limited of a solution, but couldn't you do a String.split()
on each line of the file, remembering the result array of the first line to generate the XML, and just spit each line's array data out with the proper XML elements padding each iteration of a loop?
这可能是太简单了还是有限的一个解决方案,但你不能做String.split()文件的每一行,记住第一行的结果数组生成XML,就吐每一行与适当的XML元素的数组数据填充循环的每次迭代?
#15
3
I had the same problem and needed an application to convert a CSV file to a XML file for one of my projects, but didn't find anything free and good enough on the net, so I coded my own Java Swing CSVtoXML application.
我遇到了同样的问题,需要一个应用程序来为我的一个项目将CSV文件转换为XML文件,但是在网上找不到任何免费的、足够好的东西,所以我编写了自己的Java Swing CSVtoXML应用程序。
It's available from my website HERE. Hope it will help you.
可以在我的网站上找到。希望它能对你有所帮助。
If not, you can easily code your own like I did; The source code is inside the jar file so modify it as you need if it doesn't fill your requirement.
如果没有,你可以很容易地编写自己的代码;源代码在jar文件中,因此如果不满足您的需求,可以根据需要修改它。