2016-09-26 39 views
0

私はCSVをXMLデータに変換しようとしていました。さまざまな例を見て、私はCSVファイルを解析してXMLファイルを取得するコードを書くことができました。しかし、私が書いたコードは、間違ったタグを持つXMLファイルを返します。CSVからXMLへの変換Java

これは、変換のためのコードです:

package com.adarsh.parse; 
import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.StringTokenizer; 
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.parsers.FactoryConfigurationError; 
import javax.xml.parsers.ParserConfigurationException; 
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.w3c.dom.Document; 
import org.w3c.dom.Element; 



public class Converter { 

    /* Protected members to avoid instantiation */ 
    protected DocumentBuilderFactory domFactory = null; 
    protected DocumentBuilder domBuilder = null; 
    /* Constant strings */ 
    // Input CSV file 
    final String INPUT_FILE = "sample_data.csv"; 
    // Output XML document 
    final String OUTPUT_FILE ="in.xml"; 
    // First element in the XML document 
    final String FIRST_ELEMENT="school"; 
    public Converter(){ 
     try { 
      domFactory = DocumentBuilderFactory.newInstance(); 
      /* Obtaining instance of class DocumentBuilder */ 
      domBuilder = domFactory.newDocumentBuilder(); 
     } 
     catch(ParserConfigurationException exp) { 
      System.err.println(exp.toString()); 

     } 
     catch(FactoryConfigurationError exp){ 
      System.err.println(exp.toString()); 
     } 
     catch(Exception exp){ 
      System.err.println(exp.toString()); 
     } 
    } 
    /** 
    * This method converts the given CSV file into an XML document 
    */ 
    public int convert(String csvFileName, String xmlFileName) { 
     int rowCount = -1; 
     try { 
      /* Initializing the XML document */ 
      Document newDoc = domBuilder.newDocument(); 
      /* Creating the root element in the XML */ 
      Element rootElem = newDoc.createElement(FIRST_ELEMENT); 
      newDoc.appendChild(rootElem); 
      /* Reading the CSV file */ 
      BufferedReader csvFileReader; 
      csvFileName = INPUT_FILE; 
      csvFileReader = new BufferedReader(new FileReader(csvFileName)); 
      /* Initialize the number of fields to 0 */ 
      int fieldCount = 0; 
      String[] csvFields = null; 
      StringTokenizer stringTokenizer = null; 

      /** 
      * Map the column names in the CSV file as the elements in the XML 
      * document, eliminate any other characters not eligible for XML element 
      * naming 
      */ 
      /* Initialize the current line variable */ 
      String currLine = csvFileReader.readLine(); 
      /* Loop until we reach the end of the file 
      * edge case: Empty CSV file 
      * */ 

      if(currLine != null) { 
       /* Separate fields based on commas */ 
       stringTokenizer = new StringTokenizer(currLine, ","); 
       fieldCount = stringTokenizer.countTokens(); 
       /* If there is data in the CSV file */ 
       if(fieldCount > 0) { 
        /* Initialize a String Array of Fields */ 
        csvFields = new String[fieldCount]; 
        int i = 0; 
        /* Loop till all elements are found and save fields */ 
        while (stringTokenizer.hasMoreElements()) { 
         csvFields[i++] = String.valueOf(stringTokenizer.nextElement()); 
        } 
       } 

      } 
      else { 
       System.out.println("Nothing to parse"); 
      } 
      /* reading rows from the CSV file */ 
      while((currLine = csvFileReader.readLine()) != null) { 
       stringTokenizer = new StringTokenizer(currLine, ","); 
       fieldCount = stringTokenizer.countTokens(); 
       /* if rows exist in the CSV file*/ 
       if(fieldCount > 0) { 
        /* Create the row element*/ 
        Element rowElem = newDoc.createElement("row"); 
        int i = 0; 
        /* until there are more elements*/ 
        while(stringTokenizer.hasMoreElements()) { 
         try { 
          /* Append each element found to each row element*/ 
          String currValue = String.valueOf(stringTokenizer.nextElement()); 
          Element currElem = newDoc.createElement(csvFields[i++]); 
          currElem.appendChild(newDoc.createTextNode(currValue)); 
          rowElem.appendChild(currElem); 
         } 
         catch(Exception exp) { 

         } 
        } 
        /* Append the rows to the root element*/ 
        rootElem.appendChild(rowElem); 
        rowCount++; 
       } 
      } 
      /* Finish reading the CSV file */ 
      csvFileReader.close(); 

      /* Saving the generated XML doc into required format file to disk */ 
      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); 
      xmlFileName = OUTPUT_FILE; 
      Result dest = new StreamResult(new File(xmlFileName)); 
      aTransformer.transform(src, dest); 

      rowCount++; 
     } 
     catch(IOException exp) { 
      System.err.println(exp.toString()); 
     } 
     catch(Exception exp) { 
      System.err.println(exp.toString()); 
     } 
     /* Number of rows parsed into XML */ 
     return rowCount; 

    } 

} 

これは、ファイルのサンプルCSVデータである:

classroom_id、classroom_name、teacher_1_id、teacher_1_last_name、teacher_1_first_name、teacher_2_id、teacher_2_last_name、teacher_2_first_name、スチールのPhysEdクラス、10200000001、スミス、アーサー、10200000011、、スチューデント_名、スチューデント_名_、スチューデント_ファースト_名、スチューデント_グレード 103、Brian's Homeroom、10300000001、O'Donnell、Brian、、、、、、102、 、スミスのPhysEdクラス、 、Patterson、John、10200000011、McCrancy、Brandon、1 102、Smithの PhysEdクラス、10200000001、Smith、Arthur、10200000011、Patterson、 John、10200000018、Reginald、Alexis、 10200000001、Smith、Arthur、10200000011、Patterson、John、10200000019、 Gayle、Matthew、1 102、SmithのPhysEdクラス、10200000001、Smith、 Arthur、10200000011、Patterson、John、10200000010、Smith、Nathaniel、Smith、Nathaniel、1 102 、スミス氏のPhysEdクラス、10200000001、スミス、アーサー、 10200000011、パターソン、ジョン、10200000013、Lanni、エリカ、1 102、氏 スミスさんPhysEdクラス、10200000001、スミス、アーサー、10200000011、 パターソン、ジョン、10200000014 、Flores、Michael、1 102、Smith氏のスミスのPhysEdクラス、 、10200000001、スミス、アーサー、10200000011、パターソン、ジョン、10200000016、 ペレス、ペルツェ、ペルツァン、10200000012、ペルソナ、10200000012、ジョン、10200000012、マルコ、エリザベス、1 102、ブルターニュ、1 102、スミス氏のPhysEdクラス、10200000001、スミス、 アーサー、10200000011、パターソン、ジョン、10200000015、ヒル、ジャスミン、1 102、スミスのPhysEdクラス、10200000001、スミス、アーサー、、10200000011、パターソンジョーンズの数学クラス10100000001、ジョーンズ、バーバラ、10100000015、 クルーズ、アレックス、1 101、ジョーンズの数学のクラス、10100000001、ジョーンズ、ジョン、10200000017、ハイラム、ウィリアム、10110、 Barbara、、、10100000014、Garcia、Lizzie、1 101、Mrs. Jonesの数学 クラス、10100000001、ジョーンズ、バーバラ、、10100000013、メルカド、トビー、 1ジョーンズの数学クラス、10100000001、ジョーンズ、バーバラ、、 10100000011、グティエレス、キンバリー、2 101、Mrs.ジョーンズのMathクラス、 10100000001、ジョーンズ、バーバラ、、、、10100000010、ギル、マイケル、2

私はXMLファイルに次のような出力を得るために期待していた。

<grade id="1"> 
    <classroom id="101" name="Mrs. Jones' Math Class"> 
     <teacher id="10100000001" first_name="Barbara" last_name="Jones"/> 

     <student id="10100000010" first_name="Michael" last_name="Gil"/> 
     <student id="10100000011" first_name="Kimberly" last_name="Gutierrez"/> 
     <student id="10100000013" first_name="Toby" last_name="Mercado"/> 
     <student id="10100000014" first_name="Lizzie" last_name="Garcia"/> 
     <student id="10100000015" first_name="Alex" last_name="Cruz"/> 
    </classroom> 


    <classroom id="102" name="Mr. Smith's PhysEd Class"> 
     <teacher id="10200000001" first_name="Arthur" last_name="Smith"/> 
     <teacher id="10200000011" first_name="John" last_name="Patterson"/> 

     <student id="10200000010" first_name="Nathaniel" last_name="Smith"/> 
     <student id="10200000011" first_name="Brandon" last_name="McCrancy"/> 
     <student id="10200000012" first_name="Elizabeth" last_name="Marco"/> 
     <student id="10200000013" first_name="Erica" last_name="Lanni"/> 
     <student id="10200000014" first_name="Michael" last_name="Flores"/> 
     <student id="10200000015" first_name="Jasmin" last_name="Hill"/> 
     <student id="10200000016" first_name="Brittany" last_name="Perez"/> 
     <student id="10200000017" first_name="William" last_name="Hiram"/> 
     <student id="10200000018" first_name="Alexis" last_name="Reginald"/> 
     <student id="10200000019" first_name="Matthew" last_name="Gayle"/> 
    </classroom> 

    <classroom id="103" name="Brian's Homeroom"> 
     <teacher id="10300000001" first_name="Brian" last_name="O'Donnell"/> 
    </classroom> 
</grade> 
<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<school> 
    <row> 
     <classroom_id>101</classroom_id> 
    </row> 
    <row> 
     <classroom_id>101</classroom_id> 
    </row> 
    <row> 
     <classroom_id>101</classroom_id> 
    </row> 
    <row> 
     <classroom_id>101</classroom_id> 
    </row> 
    <row> 
     <classroom_id>101</classroom_id> 
    </row> 
    <row> 
     <classroom_id>102</classroom_id> 
    </row> 
    <row> 
     <classroom_id>102</classroom_id> 
    </row> 
    <row> 
     <classroom_id>102</classroom_id> 
    </row> 
    <row> 
     <classroom_id>102</classroom_id> 
    </row> 
    <row> 
     <classroom_id>102</classroom_id> 
    </row> 
    <row> 
     <classroom_id>102</classroom_id> 
    </row> 
    <row> 
     <classroom_id>102</classroom_id> 
    </row> 
    <row> 
     <classroom_id>102</classroom_id> 
    </row> 
    <row> 
     <classroom_id>102</classroom_id> 
    </row> 
    <row> 
     <classroom_id>102</classroom_id> 
    </row> 
    <row> 
     <classroom_id>103</classroom_id> 
    </row> 
</school> 

だから、誰かがこれで私を助けてくださいことができます:

は、これは私が現在出力を取得していますどのようにでしょうか?私はどこが間違っているのだろうと思っていた。ありがとう

P.S.私はすでにstackoverflow上のCSVからXMLへの変換に関する他の質問をここで参照しています。しかし、私は、私に固有の問題に対する適切な解決策や説明を見つけることができませんでした。

P.S.このようなCSVデータをXMLに解析することが義務付けられていない場合は、XSLTの使用を提案しないでください。他に選択肢がない場合は、XSLTに関する知識がほとんどないので、XSLTを学ばなくてはなりません。あなたが既に書いたコードの変更を提案するなら、それは非常に感謝しています。

答えて

0

あなたのCSVコンテンツに改行記号の区切り記号がないようです。