将xml数据保存为CSV

时间:2016-12-07 09:02:42

标签: java xml csv parsing xml-parsing

我有一个简单的类来从光盘读取XML文件。

我不知道,如何将结果保存到CSV文件? 你能帮我吗?

package praser;   
public class ReadXML {

    public static void main(String[] args) throws Exception{

        File xmlFile = new File("C:\\test2.xml");                
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();            
        Document document = documentBuilder.parse(xmlFile);            
        NodeList list = document.getElementsByTagName("Developer");

        for (int i = 0; i < list.getLength(); i++) {

            Node node = list.item(i);                
            if(node.getNodeType() == Node.ELEMENT_NODE){                    
                Element element = (Element) node;                    
                System.out.println("Id: " + element.getAttribute("Id"));
                System.out.println("Name " + element.getElementsByTagName("Name").item(0).getTextContent());
                System.out.println("Surname " + element.getElementsByTagName("Surname").item(0).getTextContent());
                System.out.println("Age " + element.getElementsByTagName("Age").item(0).getTextContent());
            }  }}}     

我的xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Developer Id="1">
    <Name>Tom</Name>
    <Surname>Hawk</Surname>
    <Age>100</Age>

    <Name>Tom2</Name>
    <Surname>Hawk2</Surname>
    <Age>200</Age>
</Developer>

3 个答案:

答案 0 :(得分:1)

使用此代码段:

包裹普拉瑟;
公共类ReadXML {

public static void main(String[] args) throws Exception{

    File xmlFile = new File("C:\\test2.xml");                
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();            
    Document document = documentBuilder.parse(xmlFile);            
    NodeList list = document.getElementsByTagName("Developer");

Writer writer = new OutputStreamWriter(new FileOutputStream("pathToFile"), "UTF-8");
BufferedWriter bw = new BufferedWriter(writer);
String id, name, surname, age, line;

    for (int i = 0; i < list.getLength(); i++) {

        Node node = list.item(i);                
        if(node.getNodeType() == Node.ELEMENT_NODE){                    
            Element element = (Element) node;       
            id = element.getAttribute("Id");
            name = element.getElementsByTagName("Name").item(0).getTextContent();
            surname = element.getElementsByTagName("Surname").item(0).getTextContent();
            age = element.getElementsByTagName("Age").item(0).getTextContent();
            line = String.format("%s\t%s\t%s\t%s", id, name, surname, age);
            bw.write(line);
            bw.newLine();
            bw.flush();             
        }  }}} 

输入文件:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Data>
<Developer Id="1">
    <Name>Tom</Name>
    <Surname>Hawk</Surname>
    <Age>100</Age>
</Developer>
<Developer Id="2">
    <Name>jessy</Name>
    <Surname>Jay</Surname>
    <Age>16</Age>
</Developer>
</Data>

输出:

1   Tom Hawk    100
2   jessy   Jay 16

答案 1 :(得分:0)

您可以使用以下代码将内容写入csv文件。此解决方案基于以下问题中提供的初始XML。

<Developer Id="1">
  <Name>Tom</Name>
  <Surname>Hawk</Surname>
  <Age>100</Age>
</Developer>

读取此xml并将其保存到csv的代码可以使用以下java代码

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.*;

public class ReadXML {

public static void main(String[] args) throws Exception {

    File xmlFile = new File("C:\\test2.xml");
    File outputFile = new File("Output.csv");
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(xmlFile);
    NodeList list = document.getElementsByTagName("Developer");


    BufferedWriter bw = null;
    FileWriter fw = null;
    try {
        if (!outputFile.exists()) {
            outputFile.createNewFile();
        }
        // true = append file
        fw = new FileWriter(outputFile.getAbsoluteFile(), true);
        bw = new BufferedWriter(fw);

        for (int i = 0; i < list.getLength(); i++) {

            Node node = list.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                System.out.println("Id: " + element.getAttribute("Id"));
                System.out.println("Name " + element.getElementsByTagName("Name").item(0).getTextContent());
                System.out.println("Surname " + element.getElementsByTagName("Surname").item(0).getTextContent());
                System.out.println("Age " + element.getElementsByTagName("Age").item(0).getTextContent());
                bw.write(element.getAttribute("Id") + ","
                        + element.getElementsByTagName("Name").item(0).getTextContent() + ","
                        + element.getElementsByTagName("Surname").item(0).getTextContent() + ","
                        + element.getElementsByTagName("Age").item(0).getTextContent() + "," + "\n");
            }
        }

    }

    catch (IOException e) {
        // catch block
        e.printStackTrace();
    } finally {

        try {

            if (bw != null)
                bw.close();

            if (fw != null)
                fw.close();

        } catch (IOException ex) {

            ex.printStackTrace();

        }
    }

}
}

Output.csv将类似于以下屏幕。

enter image description here

答案 2 :(得分:0)

要在单独的列中获取数据,您必须使用分隔符作为逗号 ,

  1. 如果您只想要以下格式的数据而不填写特定列中的数据 示例:
ID;Name;Age
01;Deepak;22

对于上述结果,您必须使用半列 ; 作为分隔符。

  1. 如果要将数据放入列中,则必须使用逗号 , 作为分隔符。