在Java中没有获得所需的XML输出

时间:2017-07-07 06:17:00

标签: java xml csv

我正在将CSV文件转换为XML,它正在转换但没有获得所需的结构化输出。

我的java代码: -

    public static void main(String[] args){
    List<String> headers=new ArrayList<String>(5);

    File file=new File("C:/Users/Admin/Desktop/data.csv");
    BufferedReader reader=null;

    try {


        DocumentBuilderFactory domFactory =DocumentBuilderFactory.newInstance();
        DocumentBuilder domBuilder=domFactory.newDocumentBuilder();

        Document newDoc=domBuilder.newDocument();
        // Root element
        Element rootElement=newDoc.createElement("root");
        newDoc.appendChild(rootElement);

        reader = new BufferedReader(new FileReader(file));
        int line=0;

        String text=null;
        while ((text=reader.readLine())!=null) {

            StringTokenizer st=new StringTokenizer(text, "?", false);    
            String[] rowValues=new String[st.countTokens()];
            int index=0;
            while (st.hasMoreTokens()) {

                String next=st.nextToken();
                rowValues[index++]=next;

            }

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

            if (line == 0) { // Header row
                for (String col:rowValues) {
                    headers.add(col);

                    Element rowElement=newDoc.createElement("header");
                    rootElement.appendChild(rowElement);

                    for (int col1=0;col1<headers.size();col1++) {
                        String header = headers.get(col1);
                        String value = null;

                        if (col1<rowValues.length) {
                            value=rowValues[col1];
                        } else {
                            // ?? Default value
                            value=" ";
                        }
                        rowElement.setTextContent(value);
                        System.out.println(headers+" "+value);
                }

                }} else { // Data row
                Element rowElement=newDoc.createElement("row");
                rootElement.appendChild(rowElement);

                for (int col=0;col<headers.size();col++) {
                    String header = headers.get(col);
                    String value = null;

                    if (col<rowValues.length) {
                        value=rowValues[col];
                    } else {
                        // ?? Default value
                        value=" ";
                    }
                    rowElement.setTextContent(value);
                    System.out.println(header+" "+value);


                }
            }
            line++;
        }


        try {



            TransformerFactory tranFactory = TransformerFactory.newInstance();
            Transformer aTransformer = tranFactory.newTransformer();
            aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
            aTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
            aTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

            Source src = new DOMSource(newDoc);
            Result result = new StreamResult(new File("C:/Users/Admin/Desktop/data.xml"));

          aTransformer.transform(src, result);
          System.out.println("File creation successfully!");



        } catch (Exception exp) {
            exp.printStackTrace();
        } finally {
            try {


            } catch (Exception e1) {
            }
            try {

            } catch (Exception e1) {
            }
        }
    } catch (Exception e1) {
        e1.printStackTrace();
}

}

这是我的CSV文件: -

Symbol,Open,High,Low,Last Traded Price,Change
"NIFTY 50","9,645.90","9,650.65","9,600.95","9,609.30","-5.70"
"RELIANCE","1,390.00","1,414.20","1,389.00","1,407.55","26.50"
"BPCL","647.70","665.00","645.95","660.10","10.75"
"ADANIPORTS","368.50","373.80","368.00","372.25","4.25"
"ONGC","159.50","161.75","159.35","160.80","1.70"

这是我得到的输出: -

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
    <header>Symbol,Open,High,Low,Last Traded Price,Change</header>
    <row>"NIFTY 50","9,645.90","9,650.65","9,600.95","9,609.30","-5.70"</row>
    <row>"RELIANCE","1,390.00","1,414.20","1,389.00","1,407.55","26.50"</row>
    <row>"BPCL","647.70","665.00","645.95","660.10","10.75"</row>
    <row>"ADANIPORTS","368.50","373.80","368.00","372.25","4.25"</row>
    <row>"ONGC","159.50","161.75","159.35","160.80","1.70"</row>
</root>

建议我哪里出错了?我按照我的意思尝试,但是如果我在标题和行部分中进行更改,我会感到困惑。

增加: - 预期产出

<root>
<header>symbol</header>
 <row>NIFTY 50</row>
 <row>RELIANCE</row>
 <row>BPCL></row>
 .
 .
 <header>Open</header>
 <row>9,645.90</row>
 <row>1,390.00</row>
 .
 .
 </root>

1 个答案:

答案 0 :(得分:1)

供您参考:

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.csv.QuoteMode;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CsvToXml {

    public static void main(String[] args) {
        File inputFile = new File("C:/Users/Admin/Desktop/data.csv");
        CSVParser inParser = null;
        Document newDoc = null;
        try {
            inParser = CSVParser.parse(inputFile, StandardCharsets.UTF_8,
                    CSVFormat.EXCEL.withHeader().withQuoteMode(QuoteMode.NON_NUMERIC));
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder domBuilder = domFactory.newDocumentBuilder();

            newDoc = domBuilder.newDocument();
            // Root element
            Element rootElement = newDoc.createElement("root");
            newDoc.appendChild(rootElement);
            List<CSVRecord> records = inParser.getRecords();
            for (String key : inParser.getHeaderMap().keySet()) {
                Element rowElement = newDoc.createElement("header");
                rootElement.appendChild(rowElement);
                rowElement.setTextContent(key);
                for (CSVRecord record : records) {
                    rowElement = newDoc.createElement("row");
                    rootElement.appendChild(rowElement);
                    rowElement.setTextContent(record.get(key));
                }
            }
            TransformerFactory tranFactory = TransformerFactory.newInstance();
            Transformer aTransformer = tranFactory.newTransformer();
            aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
            aTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
            aTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

            Source src = new DOMSource(newDoc);
            Result result = new StreamResult(new File("C:/Users/Admin/Desktop/data.xml"));

            aTransformer.transform(src, result);
            System.out.println("File creation successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inParser != null) {
                try {
                    inParser.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

这是使用Apache Commons CSV。