I am using opencsv to parse text file and generate List<String[]> now I want to generate XML from List<String[]> and so my question is do we have any 3rd Party Libraries that does that conversion, if not, what would be an better approach to solve the issue.
Here is the Parsing Logic:
public class ParseFile {
public ParseFile() {
}
public void getQuotes() {
String fileName = "C:\\GS.txt";
try {
CSVReader reader = new CSVReader(new FileReader(fileName), '\t');
String[] nextLine;
List<String[]> dataList = new ArrayList<String[]>();
dataList = reader.readAll();
} catch (Exception e) {
}
}
public static void main(String args[]) {
ParseFile test = new ParseFile();
test.getQuotes();
System.out.println("Parsing Done Successfully....");
}
}
So my txt file looks like:
Header Information: ContractDate Trader Quantity
1st Line of Data: 03/23/12 GS 100
and I need to have XML Structure like:
<root>
<entry id='1'>
<ContractDate>03/23/12</ContractDate>
<Trader>GS</Trader>
<Quantity>100</Quantity>
</entry>
</root>
You don’t explicitly require a 3rd party library to generate your rather simple XML format. You could simply write a to a StringBuffer object:
However, I’m not necessarily advocating it. I personally recommend Simple XML. Create a POJO to model your rows (I won’t include all properties in my example):
It’s certainly some extra work up-front, but for non-trivial programs, having proper Java classes to represent the data models makes a lot of sense and provides greater flexibility, and code clarity.
To save save as XML you do this:
The Simple XML library gives you a lot of flexibility. You can also load up the XML file back into a list of Entry objects.