2013-01-31 70 views
1

我想知道是否有一种可接受的方法将管道分隔文本文件转换为Java中的XML。在分隔的文件我期待转换的格式为: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

这里有一些回答你的问题,但首先应更换用逗号隔开管道分隔符,因为它是CSVXML

您可以String类使用s.replaceAll("|",",")及以下说明做:

Conversion of CSV to XML with JAVA

Java lib or app to convert CSV to XML file?

+0

值得注意的是,任何体面的CSV库(以及第二个链接中提及的所有库)都可以处理管道分隔的文件以及CSV。如果管道分隔文件中存在某种引用字符,则建议的转换可能会有危险。 – ig0774

0

我找到了另外1种方法将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()); 
     } 
    } 
} 
相关问题