【问题标题】:Converting a CSV file to an XML file using Java使用 Java 将 CSV 文件转换为 XML 文件
【发布时间】:2016-07-21 11:00:42
【问题描述】:

我正在尝试编写一个 java 程序,它将读取不同巴士站信息的 csv 文件并将它们转换为 xml 文件并保存为新的 xml 文件。我从朋友那里得到了一些代码的帮助,但我无法理解问题出在哪里,因为他们忘记将 cmets 包含在代码中。任何修复代码的帮助将不胜感激。代码如下所示。

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、CommonName、LocalityName、ParentLocalityName、纬度、经度 0100BRP90336,The Centre,Bristol City Centre,布里斯托,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

这是我要复制的 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>

【问题讨论】:

  • 代码有什么问题?哪些方面没有达到您的预期?
  • 它没有输出和保存文件,我对这种语言没有太多经验,所以我很不确定是否缺少某些东西。我运行代码,没有任何迹象表明发生了什么事。
  • 您需要从stops.csv 中提供几行来显示预期的输入。如果您也有预期输出的简短示例,那将是最好的。
  • 编辑添加您需要的内容
  • @Granto867 欢迎来到 SO。你不应该在回答后破坏问题。它应该留在网站上,以帮助将来遇到类似问题的人。

标签: java xml csv converter


【解决方案1】:

此代码正在生成一个输出,将读取的 .csv 转换为 XML 文档(显示在标准输出上)。

根据提供的 .csv 摘录,代码运行良好,并在标准输出上生成 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>

如果不想将其显示在标准输出上而是将其写入文件,您可以简单地将标准输出重定向到文件(最简单的方法)。

否则,将System.out.println(output.toString()) 更改为写入文件。比如:

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

会起作用的。

【讨论】:

  • 我已将其更改为提供的行并运行代码,但活动没有任何变化。代码似乎没有做任何事情。我需要手动创建stops.xml 文件还是代码会为我这样做?
  • @Granto867,该代码确实有效,并根据示例 .csv 生成答案中显示的输出。我可能会建议输入stops.csv 文件的完整路径(例如,new File("c:/tmp/stops.csv")。该程序将创建一个具有在 PrintWriter 中指定的名称的 .xml 文件。(可能也应该使用完整路径)。与架构,.xml 具有“详细信息”而不是“停止”作为元素,但这很容易在代码中修复。
猜你喜欢
  • 2014-02-20
  • 2016-01-07
  • 1970-01-01
  • 2011-03-18
  • 2011-03-05
  • 2015-10-28
  • 2014-11-22
  • 2017-04-18
相关资源
最近更新 更多