2013-01-31 4 views
1

파이프로 구분 된 텍스트 파일을 Java의 XML로 변환하는 데 사용할 수있는 방법이 있는지 궁금합니다. I 변환 찾고 구분 된 파일 형식으로되어 있습니다 :Java - 파이프로 구분 된 텍스트 파일을 XML로 변환

RefNo | Location | Name | Age 
123  | North America | Steve | 32 

그리고로 변환 찾고 있어요 :

<data> 
    <RefNo>123</RefNo> 
    <location>North America</location> 
    <name> Steve </name> 
    <age> 32 </age> 
</data> 
+1

이것은 일회용입니까, 아니면 다른 제목을 가진 파일이 있습니까? – Eric

+0

또한 'RefNo'를'RefNo'로 매핑하고'Name'을'name'으로 매핑하는 규칙은 무엇입니까? – Eric

답변

1
여기

귀하의 질문에 어떤 대답을하지만, 먼저는 교체해야 파이프 분리 기호는 쉼표로 표시됩니다. CSV ~ XML입니다. 필요에 따라

Conversion of CSV to XML with JAVA

Java lib or app to convert CSV to XML file?

+0

괜찮은 CSV 라이브러리 (및 두 번째 링크에 언급 된 모든 파일)가 CSV뿐만 아니라 파이프 구분 파일도 처리 할 수 ​​있다는 점을 관찰 할 가치가 있습니다. 파이프로 구분 된 파일에 일종의 인용 문자가 있으면 잠재적으로 위험합니다. – ig0774

0

내가 CSV를 XML로 변환하는 또 다른 방법을 찾았습니다 ....

import java.io.*; 
import java.util.*; 
import org.w3c.dom.*; 
import javax.xml.parsers.*; 
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 
public class CSV2XML { 
// Protected Properties 
    protected DocumentBuilderFactory domFactory = null; 
    protected DocumentBuilder domBuilder = null; 
// CTOR 
    public CSV2XML() 
    { 
     try 
     { 
      domFactory = DocumentBuilderFactory.newInstance(); 
      domBuilder = domFactory.newDocumentBuilder(); 
     } 
     catch(FactoryConfigurationError exp) 
     { 
      System.err.println(exp.toString()); 
     } 
     catch(ParserConfigurationException exp) 
     { 
      System.err.println(exp.toString()); 
     } 
     catch(Exception exp) 
     { 
      System.err.println(exp.toString()); 
     } 
    } 
    public int convertFile(String csvFileName, String xmlFileName) 
    { 
     int rowsCount = -1; 
     try 
     { 
      Document newDoc = domBuilder.newDocument(); 
// Root element 
      Element rootElement = newDoc.createElement("CSV2XML"); 
      newDoc.appendChild(rootElement); 

// Read comma seperated file 

      BufferedReader csvReader; 
      csvFileName = "C:\\frnds.csv"; 
      csvReader = new BufferedReader(new FileReader(csvFileName)); 
      int fieldCount = 0; 
      String[] csvFields = null; 
      StringTokenizer stringTokenizer = null; 
// Assumption: first line in CSV file is column/field names 
// As the column names are used to name the elements in the XML file, 
// avoid using spaces/any other characters not suitable for XML element naming 

      String curLine = csvReader.readLine(); 
      if(curLine != null) 
      { 
       stringTokenizer = new StringTokenizer(curLine, ","); 
       fieldCount = stringTokenizer.countTokens(); 
       if(fieldCount > 0) 
       { 
        csvFields = new String[fieldCount]; 
        int i=0; 
        while(stringTokenizer.hasMoreElements()) 
         csvFields[i++] = 
           String.valueOf(stringTokenizer.nextElement()); 
       } 
      } 
// Now we know the columns, Let's now read data row lines 
      while((curLine = csvReader.readLine()) != null) 
      { 
       stringTokenizer = new StringTokenizer(curLine, ","); 
       fieldCount = stringTokenizer.countTokens(); 
       if(fieldCount > 0) 
       { 
        Element rowElement = newDoc.createElement("row"); 
        int i=0; 
        while(stringTokenizer.hasMoreElements()) 
        { 
         try 
         { 
          String curValue = 
            String.valueOf(stringTokenizer.nextElement()); 
          Element curElement = 
            newDoc.createElement(csvFields[i++]); 
          curElement.appendChild(newDoc.createTextNode(curValue)); 
          rowElement.appendChild(curElement); 
         } 
         catch(Exception exp) 
         { 
         } 
        } 
        rootElement.appendChild(rowElement); 
        rowsCount++; 
       } 
      } 
      csvReader.close(); 
// Save the document to the disk file 
      TransformerFactory tranFactory = TransformerFactory.newInstance(); 
      Transformer aTransformer = tranFactory.newTransformer(); 
      Source src = new DOMSource(newDoc); 
      xmlFileName = "C:\\stest.xml"; 
      Result dest = new StreamResult(new File(xmlFileName)); 
      aTransformer.transform(src, dest); 
      rowsCount++; 
     } 
     catch(IOException exp) 
     { 
      System.err.println(exp.toString()); 
     } 
     catch(Exception exp) 
     { 
      System.err.println(exp.toString()); 
     } 
     return rowsCount; 
    } 
    public static void main(String[] args) 
    { 
     try 
     { 
      args = new String[] {"C:\\frnds.csv", "C:\\stest.xml"}; 
      if(args.length != 2) 
      { 
       System.out.println("Usage: java CSV2XML <inputCSVFile> <outputXMLFile>"); 
       return; 
      } 
     } 
     catch(Exception exp) 
     { 
      System.err.println(exp.toString()); 
     } 
     try 
     { 
      CSV2XML csvConverter = new CSV2XML(); 
      int rowsCount = csvConverter.convertFile(args[0], args[1]); 
      if(rowsCount >= 0) 
      { 
       System.out.println("CSV File '" + args[0] + "' successfully converted to XML File '"+ args[1] + "'\n" + "(" + String.valueOf(rowsCount) + " rows)"); 
      } 
      else 
      { 
       System.out.println("Error while converting input CSV File '" + args[0] + "' to output XML File '"+ args[1] + "'"); 
      } 
     } 
     catch(Exception exp) 
     { 
      System.err.println(exp.toString()); 
     } 
    } 
} 
관련 문제