Granto867
Granto867

Reputation: 3

Converting a CSV file to an XML file using Java

I am trying to write a java program that will read in a csv file of different bus stop information and convert them to an xml file and save as the new xml file. I had some help with some code from a friend but am unable to understand what the problem is as they forgot to include comments into the code. Any help fixing the code would be greatly appreciated. Code is shown below.

public class converter {
protected DocumentBuilderFactory domFactory = null;
protected DocumentBuilder domBuilder = null;

public static void main(String[] args) {



    ArrayList<String> busStopInfo = new ArrayList<String>(7);

    File file = new File("stops.csv");
    BufferedReader readFile = null;
    try {
        DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = df.newDocumentBuilder();

        Document document = db.newDocument();

        Element rootElement = document.createElement("BusStops");

        document.appendChild(rootElement);
        readFile = new BufferedReader(new FileReader(file));
        int line = 0;

        String information = null;
        while ((information = readFile.readLine()) != null) {

            String[] rowValues = information.split(",");

            if (line == 0) {
                for (String columnInfo : rowValues) {
                    busStopInfo.add(columnInfo);
                }
            } else {
                Element childElement = document.createElement("details");
                rootElement.appendChild(childElement);


                for (int columnInfo = 0; columnInfo < busStopInfo.size(); columnInfo++) {

                    String header = busStopInfo.get(columnInfo);
                    String value = null;

                    if (columnInfo < rowValues.length) {
                        value = rowValues[columnInfo];
                    } else {
                        value = " ";
                    }

                    Element current = document.createElement(header);
                    current.appendChild(document.createTextNode(value));
                    childElement.appendChild(current);
                    System.out.println(value);
                }
            }
            line++;
        }
    Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
Writer output = new StringWriter();
tf.transform(new DOMSource(document), new StreamResult(output));
System.out.println(output.toString());
} catch (Exception e) {

    }
} 

}

Below is an Extract of the csv file

AtcoCode,CommonName,LocalityName,ParentLocalityName,Latitude,Longitude 0100BRP90336,The Centre,Bristol City Centre,Bristol,51.4543379612,-2.5978824115 0170SGA56570,UWE Entrance North,Abbey Wood,,51.50419145,-2.549547265 079073001Z,Bus Station Express Lounge,Middlesbrough,,54.5760020508,-1.2391798779 0800COC31523,Bus Station,Newquay,,50.4130339395,-5.0856695446 0800COC56586,Bus Station,Camborne,,50.2132677521,-5.2974299693

This is the schema for the xml file i am trying to replicate

<xs:element name="Busstops">

    <xs:element name="stops" minOccurs="1" maxOccurs="unbounded">
        <xs:complexType>
            <xs:sequence>
            <xs:element name="AtcoCode" type="xs:string" minOccurs="1" maxOccurs="1"/>
            <xs:element name="CommonName" type="xs:string" "minOccurs="1" maxOccurs="1"/>
            <xs:element name="LocalityName" type="xs:string" "minOccurs="1" maxOccurs="1"/>
            <xs:element name="ParentLocalityName" type="xs:string" "minOccurs="0" maxOccurs="1"/>
            <xs:element name="Longitude" type="xs:string" "minOccurs="1" maxOccurs="1"/>
            <xs:element name="Latitude" type="xs:string" "minOccurs="1" maxOccurs="1"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:sequence>

Upvotes: 0

Views: 6430

Answers (1)

KevinO
KevinO

Reputation: 4403

This code is generating an output converting a .csv that is read to an XML document (displayed on stdout).

Based upon the provided .csv excerpt, the code runs fine, and generates xml on stdout:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<BusStops>
<details>
<AtcoCode>0100BRP90336</AtcoCode>
<CommonName>The Centre</CommonName>
<LocalityName>Bristol City Centre</LocalityName>
<ParentLocalityName>Bristol</ParentLocalityName>
<Latitude>51.4543379612</Latitude>
<Longitude>-2.5978824115</Longitude>
</details>
...
</BusStops>

If instead of wanting to display it on stdout but write it to a file, you could simply redirect stdout to a file (the easiest approach).

Otherwise, change the System.out.println(output.toString()) to write to a file. Something like:

PrintWriter writer = new PrintWriter("the-file-name.xml", "UTF-8");
writer.println(output.toString());
writer.close();

will work.

Upvotes: 0

Related Questions