簡體   English   中英

使用Java將CSV文件轉換為XML文件

[英]Converting a CSV file to an XML file using Java

我正在嘗試編寫一個Java程序,該程序將讀取不同公交車站信息的csv文件並將其轉換為xml文件並另存為新的xml文件。 我從朋友那里獲得了一些代碼方面的幫助,但是由於他們忘記在代碼中包含注釋,因此無法理解問題出在哪里。 修復代碼的任何幫助將不勝感激。 代碼如下所示。

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) {

    }
} 

}

以下是csv文件的摘錄

AtcoCode,通用名稱,位置名稱,父母位置名稱,緯度,經度0100BRP90336,中心,布里斯托爾市中心,布里斯托爾,51.4543379612,-2.5978824115 0170SGA56570,UWE入口北,艾比伍德,, 51.50419145,-2.549547265 079073001Z,公共汽車總站休息室,Middle 54.5760020508,-1.2391798779 0800COC31523,紐基汽車站,50.4130339395,-5.0856695446 0800COC56586,汽車站,Camborne,50.2132677521,-5.2974299693

這是我要復制的xml文件的架構

<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>

這段代碼將生成一個輸出,將一個.csv轉換為一個XML文檔(顯示在stdout上)。

根據提供的.csv摘錄,代碼可以正常運行,並在stdout上生成xml:

<?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>

如果不想將其顯示在stdout上而是將其寫入文件,則只需將stdout重定向到文件即可(最簡單的方法)。

否則,更改System.out.println(output.toString())以寫入文件。 就像是:

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

將工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM