Link to home
Start Free TrialLog in
Avatar of ramadevimandala
ramadevimandalaFlag for India

asked on

Generating XML form CSV using XSL or java

Hi ,

I am generating the below xml for CSV using ricebridge.xmlman opensource api, can anybody please suggest any other free opensource api to do the same functionality.
Or if we can do with XSL please provide the XSL code.
Thanks.
XML:
 
<?xml version='1.0' encoding='UTF-8'?>
<ROWSET>
  <ROW>
    <EMPLOYEE_FULL_NAME>Lamprecht, Mr. Mike</EMPLOYEE_FULL_NAME>
    <ASSIGNMENT_NUMBER>201</ASSIGNMENT_NUMBER>
    <EMPLOYEE_NUMBER>201</EMPLOYEE_NUMBER>
    <EMPLOYMENT_CATEGORY>Fulltime-Regular</EMPLOYMENT_CATEGORY>
    <DATE_OF_HIRE>01-JAN-98</DATE_OF_HIRE>
    <GENDER>M</GENDER>
    <ASSIGNMENT_STATUS>Active Assignment</ASSIGNMENT_STATUS>
    <DATE_OF_BIRTH>09-MAY-65</DATE_OF_BIRTH>
    <JOB_NAME>VP300.Vice President</JOB_NAME>
    <MARITAL_STATUS>Married</MARITAL_STATUS>
    <SUPERVISOR_FULL_NAME>Andretti, Mr. Evan</SUPERVISOR_FULL_NAME>
    <PAYROLL_NAME>Vision HR Semi-Monthly</PAYROLL_NAME>
    <GRADE_NAME>100.1.South</GRADE_NAME>
    <ETHNIC_ORIGIN>White</ETHNIC_ORIGIN>
    <SOCIAL_SECURITY_NUMBER>367-98-3283</SOCIAL_SECURITY_NUMBER>
    <LOCATION_NAME>VA- Philadelphia</LOCATION_NAME>
    <GOVERNMENT_REPORTING_ENTITY>Vision Services</GOVERNMENT_REPORTING_ENTITY>
    <ORGANIZATION_NAME>Vision Services</ORGANIZATION_NAME>
    <PAY_BASIS>MONTHLY</PAY_BASIS>
    <PERSON_TYPE>Employee</PERSON_TYPE>
    <LATEST_HIRE_DATE>01-JAN-98</LATEST_HIRE_DATE>
    <ADDRESS_LINE1>983 Mainstream Ave</ADDRESS_LINE1>
    <ADDRESS_CITY>Atlanta</ADDRESS_CITY>
    <ADDRESS_STATE>Georgia</ADDRESS_STATE>
    <ADDRESS_ZIP>30010</ADDRESS_ZIP>
    <LENGTH_OF_SERVICE>11.35</LENGTH_OF_SERVICE>
  </ROW>
  <ROW>
    <EMPLOYEE_FULL_NAME>Thomas, Cindy</EMPLOYEE_FULL_NAME>
    <ASSIGNMENT_NUMBER>226</ASSIGNMENT_NUMBER>
    <EMPLOYEE_NUMBER>226</EMPLOYEE_NUMBER>
    <EMPLOYMENT_CATEGORY>Fulltime-Regular</EMPLOYMENT_CATEGORY>
    <DATE_OF_HIRE>01-JAN-99</DATE_OF_HIRE>
    <GENDER>F</GENDER>
    <ASSIGNMENT_STATUS>Active Assignment</ASSIGNMENT_STATUS>
    <DATE_OF_BIRTH>10-AUG-68</DATE_OF_BIRTH>
    <JOB_NAME></JOB_NAME>
    <MARITAL_STATUS>Married</MARITAL_STATUS>
    <SUPERVISOR_FULL_NAME></SUPERVISOR_FULL_NAME>
    <PAYROLL_NAME></PAYROLL_NAME>
    <GRADE_NAME></GRADE_NAME>
    <ETHNIC_ORIGIN>White</ETHNIC_ORIGIN>
    <SOCIAL_SECURITY_NUMBER>222-11-3333</SOCIAL_SECURITY_NUMBER>
    <LOCATION_NAME>VA- Philadelphia</LOCATION_NAME>
    <GOVERNMENT_REPORTING_ENTITY>Vision Services</GOVERNMENT_REPORTING_ENTITY>
    <ORGANIZATION_NAME>Vision Services</ORGANIZATION_NAME>
    <PAY_BASIS></PAY_BASIS>
    <PERSON_TYPE>Employee</PERSON_TYPE>
    <LATEST_HIRE_DATE>01-JAN-99</LATEST_HIRE_DATE>
    <ADDRESS_LINE1>4 Saw Mill Ct.</ADDRESS_LINE1>
    <ADDRESS_CITY>Philadelphia</ADDRESS_CITY>
    <ADDRESS_STATE>Pennsylvania</ADDRESS_STATE>
    <ADDRESS_ZIP>19038</ADDRESS_ZIP>
    <LENGTH_OF_SERVICE>10.35</LENGTH_OF_SERVICE>
  </ROW>
  <ROW>
    <EMPLOYEE_FULL_NAME>Che:n, Tony</EMPLOYEE_FULL_NAME>
    <ASSIGNMENT_NUMBER>227</ASSIGNMENT_NUMBER>
    <EMPLOYEE_NUMBER>227</EMPLOYEE_NUMBER>
    <EMPLOYMENT_CATEGORY>Fulltime-Regular</EMPLOYMENT_CATEGORY>
    <DATE_OF_HIRE>01-JAN-99</DATE_OF_HIRE>
    <GENDER>M</GENDER>
    <ASSIGNMENT_STATUS>Active Assignment</ASSIGNMENT_STATUS>
    <DATE_OF_BIRTH>28-SEP-63</DATE_OF_BIRTH>
    <JOB_NAME></JOB_NAME>
    <MARITAL_STATUS>Married</MARITAL_STATUS>
    <SUPERVISOR_FULL_NAME>Thomas, Cindy</SUPERVISOR_FULL_NAME>
    <PAYROLL_NAME></PAYROLL_NAME>
    <GRADE_NAME></GRADE_NAME>
    <ETHNIC_ORIGIN>White</ETHNIC_ORIGIN>
    <SOCIAL_SECURITY_NUMBER>149-21-9421</SOCIAL_SECURITY_NUMBER>
    <LOCATION_NAME>VA- Philadelphia</LOCATION_NAME>
    <GOVERNMENT_REPORTING_ENTITY>Vision Services</GOVERNMENT_REPORTING_ENTITY>
    <ORGANIZATION_NAME>Vision Services</ORGANIZATION_NAME>
    <PAY_BASIS></PAY_BASIS>
    <PERSON_TYPE>Employee</PERSON_TYPE>
    <LATEST_HIRE_DATE>01-JAN-99</LATEST_HIRE_DATE>
    <ADDRESS_LINE1>14 Broad St.</ADDRESS_LINE1>
    <ADDRESS_CITY>Philadelphia</ADDRESS_CITY>
    <ADDRESS_STATE>Pennsylvania</ADDRESS_STATE>
    <ADDRESS_ZIP>19092</ADDRESS_ZIP>
    <LENGTH_OF_SERVICE>10.35</LENGTH_OF_SERVICE>
  </ROW>
  <ROW>
    <EMPLOYEE_FULL_NAME>Noe, Renee</EMPLOYEE_FULL_NAME>
    <ASSIGNMENT_NUMBER>228</ASSIGNMENT_NUMBER>
    <EMPLOYEE_NUMBER>228</EMPLOYEE_NUMBER>
    <EMPLOYMENT_CATEGORY>Fulltime-Regular</EMPLOYMENT_CATEGORY>
    <DATE_OF_HIRE>01-JAN-99</DATE_OF_HIRE>
    <GENDER>F</GENDER>
    <ASSIGNMENT_STATUS>Active Assignment</ASSIGNMENT_STATUS>
    <DATE_OF_BIRTH>12-FEB-68</DATE_OF_BIRTH>
    <JOB_NAME>MGR500.Manager</JOB_NAME>
    <MARITAL_STATUS>Married</MARITAL_STATUS>
    <SUPERVISOR_FULL_NAME>Ang, Ms. Lay Kuan</SUPERVISOR_FULL_NAME>
    <PAYROLL_NAME>Vision Monthly</PAYROLL_NAME>
    <GRADE_NAME></GRADE_NAME>
    <ETHNIC_ORIGIN>Black or African American</ETHNIC_ORIGIN>
    <SOCIAL_SECURITY_NUMBER>214-19-4219</SOCIAL_SECURITY_NUMBER>
    <LOCATION_NAME>VS- Washington DC</LOCATION_NAME>
    <GOVERNMENT_REPORTING_ENTITY>Vision Operations</GOVERNMENT_REPORTING_ENTITY>
    <ORGANIZATION_NAME>Vision Administration</ORGANIZATION_NAME>
    <PAY_BASIS>MONTHLY</PAY_BASIS>
    <PERSON_TYPE>Employee</PERSON_TYPE>
    <LATEST_HIRE_DATE>01-JAN-99</LATEST_HIRE_DATE>
    <ADDRESS_LINE1>17 Chestnut St.</ADDRESS_LINE1>
    <ADDRESS_CITY>Philadelphia</ADDRESS_CITY>
    <ADDRESS_STATE>Pennsylvania</ADDRESS_STATE>
    <ADDRESS_ZIP>19092</ADDRESS_ZIP>
    <LENGTH_OF_SERVICE>10.35</LENGTH_OF_SERVICE>
  </ROW>
  <ROW>
    <EMPLOYEE_FULL_NAME>Cochran, Mr. Bob</EMPLOYEE_FULL_NAME>
    <ASSIGNMENT_NUMBER>396</ASSIGNMENT_NUMBER>
    <EMPLOYEE_NUMBER>396</EMPLOYEE_NUMBER>
    <EMPLOYMENT_CATEGORY>Fulltime-Regular</EMPLOYMENT_CATEGORY>
    <DATE_OF_HIRE>05-FEB-00</DATE_OF_HIRE>
    <GENDER>M</GENDER>
    <ASSIGNMENT_STATUS>Active Assignment</ASSIGNMENT_STATUS>
    <DATE_OF_BIRTH>12-DEC-64</DATE_OF_BIRTH>
    <JOB_NAME>STA700.Staff Administrator</JOB_NAME>
    <MARITAL_STATUS></MARITAL_STATUS>
    <SUPERVISOR_FULL_NAME>Gray, Mr. Donald R</SUPERVISOR_FULL_NAME>
    <PAYROLL_NAME>Vision Semi'monthly</PAYROLL_NAME>
    <GRADE_NAME></GRADE_NAME>
    <ETHNIC_ORIGIN>White</ETHNIC_ORIGIN>
    <SOCIAL_SECURITY_NUMBER>553-34-9238</SOCIAL_SECURITY_NUMBER>
    <LOCATION_NAME>VS- Washington DC</LOCATION_NAME>
    <GOVERNMENT_REPORTING_ENTITY>Vision Services</GOVERNMENT_REPORTING_ENTITY>
    <ORGANIZATION_NAME>Vision Administration</ORGANIZATION_NAME>
    <PAY_BASIS>MONTHLY</PAY_BASIS>
    <PERSON_TYPE>Employee</PERSON_TYPE>
    <LATEST_HIRE_DATE>05-FEB-00</LATEST_HIRE_DATE>
    <ADDRESS_LINE1>77431 Coolie Court</ADDRESS_LINE1>
    <ADDRESS_CITY>Paramus</ADDRESS_CITY>
    <ADDRESS_STATE>New Jersey</ADDRESS_STATE>
    <ADDRESS_ZIP>07652</ADDRESS_ZIP>
    <LENGTH_OF_SERVICE>9.25</LENGTH_OF_SERVICE>
  </ROW>
</ROWSET>
 
 
CSV:
 
Employee Full Name,Assignment Number,Employee Number,Employment Category,Date Of Hire,Gender,Assignment Status,Date Of Birth,Job Name,Position Name,Marital Status,Supervisor Full Name,Payroll Name,Grade Name,Ethnic Origin,Social Security Number,Location Name,Government Reporting Entity,Organization Name,Pay Basis,Person Type,Adjusted Service Date,Latest Hire Date,Address Line1,Address City,Address State,Address Zip,Length Of Service,Notified Termination Date
"Lamprecht, Mr. Mike",201,201,Fulltime-Regular,01-JAN-98,M,Active Assignment,09-MAY-65,VP300.Vice President,,Married,"Andretti, Mr. Evan",Vision HR Semi-Monthly,100.1.South,White,367-98-3283,VA- Philadelphia,Vision Services,Vision Services,MONTHLY,Employee,,01-JAN-98,983 Mainstream Ave,Atlanta,Georgia,30010,11.35,
"Thomas, Cindy",226,226,Fulltime-Regular,01-JAN-99,F,Active Assignment,10-AUG-68,,,Married,,,,White,222-11-3333,VA- Philadelphia,Vision Services,Vision Services,,Employee,,01-JAN-99,4 Saw Mill Ct.,Philadelphia,Pennsylvania,19038,10.35,
"Che:n, Tony",227,227,Fulltime-Regular,01-JAN-99,M,Active Assignment,28-SEP-63,,,Married,"Thomas, Cindy",,,White,149-21-9421,VA- Philadelphia,Vision Services,Vision Services,,Employee,,01-JAN-99,14 Broad St.,Philadelphia,Pennsylvania,19092,10.35,
"Noe, Renee",228,228,Fulltime-Regular,01-JAN-99,F,Active Assignment,12-FEB-68,MGR500.Manager,510.PROJECT MANAGER,Married,"Ang, Ms. Lay Kuan",Vision Monthly,,Black or African American,214-19-4219,VS- Washington DC,Vision Operations,Vision Administration,MONTHLY,Employee,,01-JAN-99,17 Chestnut St.,Philadelphia,Pennsylvania,19092,10.35,
"Cochran, Mr. Bob",396,396,Fulltime-Regular,05-FEB-00,M,Active Assignment,12-DEC-64,STA700.Staff Administrator,710.ADMIN ASSISTANT,,"Gray, Mr. Donald R",Vision Semi'monthly,,White,553-34-9238,VS- Washington DC,Vision Services,Vision Administration,MONTHLY,Employee,,05-FEB-00,77431 Coolie Court,Paramus,New Jersey,07652,9.25,
 
 
Java Code:
 
import com.ricebridge.xmlman.XmlManager;
import com.ricebridge.xmlman.RecordSpec;
import com.ricebridge.xmlman.XmlSpec;
 
import com.ricebridge.csvman.CsvManager;
import com.ricebridge.csvman.CsvSpec;
 
import java.util.*;
import java.io.*;
 
 
/** Convert a CSV file into an XML file.
 *    In this example, the entire CSV file is loaded into memory. 
 *  This is the simplest case, and it will work so long as you have enough 
 *  memory to hold all the data. If you are dealing with multi-gigabyte files, 
 *  it is better to use the streaming solution: StreamingCsv2Xml.java
 *    For this example, the source file is report.csv. This file was exported
 *  from the Google Adwords report system, so it is the actual data format used
 *  by Google (the values have been changed, however). We have deliberately
 *  used an external CSV file to demonstrate the flexibility of the CSV and
 *  XML Manager components.
 */
public class Csv2Xml {
 
  // public methods
 
  public static void main( String[] args ) {
    File csv = new File("Employee Report10595v1.csv");
    File xml = new File("first.xml");
 
    convert( csv, xml );
  }
 
 
  public static void convert( File pCsvFile, File pXmlFile ) {
 
    // Create the CsvManager that we will use.
    // Actual data only starts on the 8th line.
    CsvManager csvman  = new CsvManager();
    CsvSpec    csvspec = csvman.getCsvSpec();
    csvspec.setEncoding("UTF-8");
    csvspec.setStartLine(2);
 
    // Also create the XmlManager, and
    // set the standard XML header (this is optional).
    XmlManager xmlman  = new XmlManager();
    XmlSpec xmlspec = xmlman.getXmlSpec();
    xmlspec.setHeader( "<?xml version='1.0' encoding='UTF-8'?>\n" );
 
    // Specify the format of the output XML.
    // Notice that the first three fields are absolute. The data records
    // will be grouped by these fields, as parent XML elements.
    String[] fieldpaths 
      = new String[] { 
        "/ROWSET/ROW/EMPLOYEE_FULL_NAME",
	      "ASSIGNMENT_NUMBER",
	      "EMPLOYEE_NUMBER",
	      "EMPLOYMENT_CATEGORY",
	      "DATE_OF_HIRE",
	      "GENDER",
	      "ASSIGNMENT_STATUS",
	      "DATE_OF_BIRTH",
	      "JOB_NAME","",
	      "MARITAL_STATUS",
	      "SUPERVISOR_FULL_NAME",
	      "PAYROLL_NAME",
	      "GRADE_NAME",
	      "ETHNIC_ORIGIN",
	      "SOCIAL_SECURITY_NUMBER",
	      "LOCATION_NAME",
	      "GOVERNMENT_REPORTING_ENTITY",
	      "ORGANIZATION_NAME",
	      "PAY_BASIS",
	      "PERSON_TYPE","",
	      "LATEST_HIRE_DATE",
	      "ADDRESS_LINE1",
	      "ADDRESS_CITY",
	      "ADDRESS_STATE",
	      "ADDRESS_ZIP",
	      "LENGTH_OF_SERVICE",
      };
    
    // The RecordSpec specifies the main record element: keyword
    RecordSpec keyspec
      = new RecordSpec("/ROWSET/ROW", fieldpaths );
    
    // Load all the CSV data.
    List csvdata = csvman.load( pCsvFile );
 
    // Last line is totals, so remove it.
    //csvdata.remove( csvdata.size()-1 );
 
    // Save the data records as XML.
    xmlman.save( pXmlFile, keyspec, csvdata );
  }
 
}

Open in new window

Avatar of Gertone (Geert Bormans)
Gertone (Geert Bormans)
Flag of Belgium image

You could read recommendations about doing this in XSLT
- wrap a starttag in front of the file and an endtag at the end and do XSLT2 regular expressions to get the stuff doen
You could even succeed with that, but I highly recommend you to not do that
XSLT is for XML processing, not for XML creation from data that is not XML

There are tons of tools that could do this, and I bet that I can hack a ruby program that does this for you in less than half an hour.

But what interests me is this: if you have a working solution, why would you change it then? Why are you unhappy with your current approach? It seems a legitimate way of doing what you need
why make a double pass with an excel library if all you need is CSV?
I think in your answer try to explain what jexcelapi does better than what the OP currently uses
Avatar of ramadevimandala

ASKER

The current approach done with the trial version  we need to purchase the licence to do that.
Ya I will try with some other tool to do the same.
Ah OK, I now see why you would be doing this

Is the license really worth more than having to redevelop your code?
I assume you are not distributing the code, so you could get away with a single developper license for 170$

Do you want to wrap this code in a javaprogram?

There is a batchconverter here
http://www.batchconverter.com/TexttoxmltabtoxmlcsvtoxmlsoftwaretoconverttextcsvandtabdelimitedfilestoxmlSoftware-download-73628.shtml

but if you can regex the lines in an array
and escape the sensitive XML characters from each field,
this is an easy Java program to develop yourself

Depending on your budget, I would stick to what seems to work
SOLUTION
Avatar of Gibu George
Gibu George
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I have already tried converting the CSv to excel and then converting to XMl using Apache POI and that is also working fine but here unnecessarily passing thru Excel.

Hi Gertone,

how can I use the batchconverter  in my java file?
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ok sure , thank you very much.

I have tried in this:
http://andrewjwelch.com/code/xslt/csv/csv-to-xml_v2.html
but not able to apply to my case, if u can find any info please help.
I have written the code in java to convert csv to xml.
and this works fine for me
/*
Creating XML document
Converts CSV file to XML
First line in CSV file is field/column names -
which is also used as element names while creating XML
document
 
CSV to XML
This class reads a CSV file and creates an XML document from it. The first line in the CSV
file is assumed to be the field/column names, and these names are used as element names in
the XML document. We call newDocument method on DocumentBuilder. This method returns an   
instance of org.w3c.dom.Document class that is then used to create XML document by calling
methods such as createElement and appendChild.
Creating XML Document using DOM (CSV2XML.java)
 
The main function creates an instance of CSV2XML class and calls convertFile method. This
method starts reading the CSV file. It uses stringTokenizer to first get the column names
(from the first row) and then the actual data items (for each row starting second row in the
file) and creates XML elements.
The above code uses JAXP classes TransformerFactory and Transformer to save the
document. The alternative approach would be to use org.apache.crimson.tree.XmlDocument
class as below:
BufferedWriter bufferWriter =
new BufferedWriter(new FileWriter(xmlFileName));
XmlDocument xDoc = (XmlDocument)newDoc;
xDoc.write(bufferWriter);
bufferWriter.close();
*/
 
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class CSV2XML {
// Protected Properties
    protected DocumentBuilderFactory domFactory = null;
    protected DocumentBuilder domBuilder = null;
 
    public CSV2XML()
    {
        try
        {
            domFactory = DocumentBuilderFactory.newInstance();
            domBuilder = domFactory.newDocumentBuilder();
        }
        catch(FactoryConfigurationError exp)
        {
            System.err.println(exp.toString());
        }
        catch(ParserConfigurationException exp)
        {
            System.err.println(exp.toString());
        }
        catch(Exception exp)
        {
            System.err.println(exp.toString());
        }
    }
    public int convertFile(String csvFileName, String xmlFileName)
    {
        int rowsCount = -1;
        try
        {
            Document newDoc = domBuilder.newDocument();
// Root element
            Element rootElement = newDoc.createElement("ROWSET");
            newDoc.appendChild(rootElement);
// Read comma seperated file
            BufferedReader csvReader;
            csvReader = new BufferedReader(new
                    FileReader(csvFileName));
            int fieldCount = 0;
            String[] csvFields = null;
            StringTokenizer stringTokenizer = null;
// Assumption: first line in CSV file is column/field names
// As the column names are used to name the elements inthe XML file,
// avoid using spaces/any other characters not suitable for XML element naming
            String curLine = csvReader.readLine();
            if(curLine != null)
            {
                stringTokenizer = new StringTokenizer(curLine, ",");
                fieldCount = stringTokenizer.countTokens();
                if(fieldCount > 0)
                {
                    csvFields = new String[fieldCount];
                    int i=0;
                    while(stringTokenizer.hasMoreElements()){
                        csvFields[i++] =
                                String.valueOf(stringTokenizer.nextElement());
             
                    }
                }
            }
            
            for(int i=0;i<csvFields.length;i++){
            	String csvField=csvFields[i].toUpperCase();
            	csvFields[i]=csvField.replaceAll(" ","_");
            	
            }
// Now we know the columns, Let's now read data row lines
            while((curLine = csvReader.readLine()) != null)
            {
            	String strArr[] = curLine.split(",");
            	String result ="";
            	 String temp ="";
            	for ( int i =0 ;i<strArr.length;i++)
            	{
            	  if( strArr[i].equals(""))
            	    temp = "(Blanks),";
            	 else
            	    temp = strArr[i] + ",";
            	result = result +  temp;
            	}
            	
            	curLine=result;
            	
            	int pp = 0;
            	  while (true) {
            	    int found = curLine.indexOf("\"", pp);
            	    if (found == -1) break;
            	    int start = found + 1; // start of actual quote
            	    int end = curLine.indexOf("\"", start);
            	    
            	    String str1=curLine.substring(start, end);
            	    str1=str1.replaceAll(",","");
            	    String str2="";
            	    str2=curLine.substring(end+1, curLine.length());
            	    
            	    if(found!=0){
            	    	curLine=curLine.substring(0, start-1)+str1+str2;
            	    	
            	    }
            	    else{
            	     	curLine=str1+str2;
            	        
            	    }
            	    pp = end + 1;  // advance i to start the next iteration
            	  }
				
                stringTokenizer = new StringTokenizer(curLine, ",");
                fieldCount = stringTokenizer.countTokens();
                if(fieldCount > 0)
                {
                    Element rowElement = newDoc.createElement("ROW");
                    int i=0;
                    while(stringTokenizer.hasMoreElements())
                    {
                        try
                        {
                            String curValue =
                                    String.valueOf(stringTokenizer.nextElement());
                            Element curElement =
                                    newDoc.createElement(csvFields[i++]);
                            curElement.appendChild(newDoc.createTextNode(curValue));
                            rowElement.appendChild(curElement);
                        }
                        catch(Exception exp)
                        {
                        }
                    }
                    rootElement.appendChild(rowElement);
                    rowsCount++;
                }
            }
            		
            csvReader.close();
// Save the document to the disk file
            TransformerFactory tranFactory =
                    TransformerFactory.newInstance();
            Transformer aTransformer = tranFactory.newTransformer();
            Source src = new DOMSource(newDoc);
            Result dest = new StreamResult(new File(xmlFileName));
            aTransformer.transform(src, dest);
            rowsCount++;
        }
        catch(IOException exp)
        {
            System.err.println(exp.toString());
        }
        catch(Exception exp)
        {
            System.err.println(exp.toString());
        }
        return rowsCount;
    }
    public static void main(String[] args)
    {
    	args=new String[2];
    	args[0]="Employee Report10595v1.csv";
    	args[1]="second.xml";
        try
        {
            if(args.length != 2)
            {
                System.out.println("Usage: java CSV2XML <inputCSVFile><outputXMLFile>");
                return;
            }
        }
        catch(Exception exp)
        {
            System.err.println(exp.toString());
        }
        try
        {
            CSV2XML csvConverter = new CSV2XML();
            int rowsCount = csvConverter.convertFile(args[0], args[1]);
            if(rowsCount >= 0)
            {
                System.out.println("CSV File '" + args[0] +
                        "' successfully converted to XML File '"+
                        args[1] + "'\n" +
                        "(" + String.valueOf(rowsCount) + " rows)");
//              set the TransformFactory to use the Saxon TransformerFactoryImpl method   
                System.setProperty("javax.xml.transform.TransformerFactory",  
                "net.sf.saxon.TransformerFactoryImpl");     
                TransformerFactory factory = TransformerFactory.newInstance();
                Templates template = factory.newTemplates(
                   new StreamSource(new FileInputStream("detailed.xslt")));
                Transformer transformer = template.newTransformer();
                Source source = new StreamSource(new FileInputStream("second.xml"));
                Result result = new StreamResult(new FileOutputStream("summary.xml"));
                transformer.transform(source, result);
 
            }
            else
            {
                System.out.println("Error while converting input CSV File '" + args[0] +
                "' to output XML File '"+ args[1] + "'");
            }
        }
        catch(Exception exp)
        {
            System.err.println(exp.toString());
        }
    }
}

Open in new window