2017-07-07 41 views
0

我將CSV文件轉換爲XML,它正在轉換,但沒有獲得所需的結構化輸出。沒有在Java中獲得所需的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

你想做什麼? –

+1

如果您向我們展示您的預期產出,您可以得到答案。 –

+0

您應該使用像Apache Commons CSV這樣的CSV庫,並且絕對不應該使用'StringTokenizer',這是古老而且不好的,不應該被任何人用於任何事情。 * StringTokenizer是一個遺留類,爲了兼容性的原因保留下來,儘管它在新代碼中的使用不受歡迎。* –

回答

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的百科全書CSV。

+0

非常感謝您,先生,現在正在工作。 – WhoAmI