A simple CSV-to-XML Converter. This is just a proof-of-concept. We can add lot of flush into it depending upon the requirement. Concept is simple. Along with the CSV file (data), provide another file with xml tags corresponding to each field in the CSV file. Read line by line from the CSV data file and prepare the XML nodes using the tag file.
Sample CSV data file
1, Bill Clinton, 56, President, United States of America
2, Sonia, 55, CEO, ABC Limited
Sample CSV tag file
id, name,age, designation, company
Source Code
public String generateXML(String tagFile, String sourceFile) {
StringBuffer buf = new StringBuffer();
String tagLine = "";
String dataLine = "";
//read tagFile and get the line
String []tags = tagLine.split(",");
buf.append("<" + rootTag + ">\n");
//read Source file and read line by line and invoke generateXMLNode.
while (....) {
buf.append(generateXMLNode(tags, dataLine));
}
buf.append("");
return buf.toString();
}
public String generateXMLNode (String []tags, String data) {
StringBuffer buf = new StringBuffer();
String []dataElements = data.split(",");
buf.append("\t<" + nodeTag + ">\n");
for (int i = 0; i <>");
buf.append(dataElements[i]);
buf.append("\n");
}
buf.append("\t<" + nodeTag + ">\n");
return buf.toString();
}
There is no proper standard for CSV. Here I have taken a simple CSV file, but in actual cases may have coma and carriage returns inside the data elements.
Showing posts with label CSV. Show all posts
Showing posts with label CSV. Show all posts
Friday, November 23, 2007
Subscribe to:
Posts (Atom)