使用JAVA将CSV转换为XML [英] Conversion of CSV to XML with JAVA

查看:150
本文介绍了使用JAVA将CSV转换为XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组CSV数据要转换为XML。代码看起来OK,但输出不够完美。



这是我的CSV数据示例:

这是一个CSV数据示例,因为它没有值,并且生成一长串XML数据,

 姓名年龄性别
chi 23
kay 19男性
John男性

而我的代码:

  public class XMLCreators {
//受保护的属性
protected DocumentBuilderFactory domFactory = null;
protected DocumentBuilder domBuilder = null;

public XMLCreators(){
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,
String delimiter){

int rowsCount = -1;
try {
Document newDoc = domBuilder.newDocument();
//根元素
元素rootElement = newDoc.createElement(XMLCreators);
newDoc.appendChild(rootElement);
//读取csv文件
BufferedReader csvReader;
csvReader = new BufferedReader(new FileReader(csvFileName));
int fieldCount = 0;
String [] csvFields = null;
StringTokenizer stringTokenizer = null;

//假设CSV文件中的第一行是列/字段名称
//列名称用于命名XML文件中的元素,
//避免使用空格或其他不适合XML元素的字符
//命名

String curLine = csvReader.readLine();
if(curLine!= null){
//其他形式的csv文件怎么样?
stringTokenizer = new StringTokenizer(curLine,delimiter);
fieldCount = stringTokenizer.countTokens();
if(fieldCount> 0){
csvFields = new String [fieldCount];
int i = 0;
while(stringTokenizer.hasMoreElements())
csvFields [i ++] = String.valueOf(stringTokenizer.nextElement());
}
}

//此时,coulmns是已知的,现在通过行读取数据
while((curLine = csvReader.readLine())!= null){
stringTokenizer = new StringTokenizer(curLine,delimiter);
fieldCount = stringTokenizer.countTokens();
if(fieldCount> 0){
元素rowElement = newDoc.createElement(row);
int i = 0;
while(stringTokenizer.hasMoreElements()){
try {
String curValue = String.valueOf(stringTokenizer.nextElement());
元素curElement = newDoc.createElement(csvFields [i ++]);
curElement.appendChild(newDoc.createTextNode(curValue));
rowElement.appendChild(curElement);
} catch(Exception exp){
}
}
rootElement.appendChild(rowElement);
rowsCount ++;
}
}
csvReader.close();

//将文档保存到磁盘文件
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
源src = new DOMSource(newDoc);
结果result = new StreamResult(new File(xmlFileName));
aTransformer.transform(src,result);
rowsCount ++;

//输出到控制台进行测试
// Resultt result = new StreamResult(System.out);

} catch(IOException exp){
System.err.println(exp.toString());
} catch(Exception exp){
System.err.println(exp.toString());
}
return rowsCount;
//XLM文档已创建+ rowsCount;
}
}

当对上述数据执行此代码时, :

 <?xml version =1.0encoding =UTF-8? ; 
< XMLCreators>
< row>
< Name> chi< / Name>
< Age> 23< / Age>
< / row>
< row>
< Name> kay< / Name>
< Age> 19< / Age>
< sex>男性< / sex>
< / row>
< row>
< Name> john< / Name>
< Age> male< / Age>
< / row>
< / XMLCreators>

我自己安排在这种形式,但输出产生一个长线。要产生的输出应为:

 <?xml version =1.0encoding = UTF-8?> 
< XMLCreators>
< row>
< Name> chi< / Name>
< Age> 23< / Age>
< sex>< / sex>
< / row>
< row>
< Name> kay< / Name>
< Age> 19< / Age>
< sex>男性< / sex>
< / row>
< row>
< Name> john< / Name>
< Age>< / Age>
< sex>男性< / sex>
< / row>
< / XMLCreators>


解决方案

我同意Kennet。

我只是添加了

  aTransformer .setOutputProperty(OutputKeys.INDENT,yes) ; 
aTransformer .setOutputProperty(OutputKeys.METHOD,xml);
aTransformer .setOutputProperty({http://xml.apache.org/xslt}indent-amount,4);

这在元素之间添加了一行并允许缩进。



UPDATED



让我们从您提供的文件不是CSV(逗号分隔值)文件,我会让你担心这个问题...

  List< String> headers = new ArrayList< String>(5); 

文件file = new File(Names2.csv);
BufferedReader reader = null;

try {

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

文档newDoc = domBuilder.newDocument();
//根元素
元素rootElement = newDoc.createElement(XMLCreators);
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){//标题行
for(String col:rowValues){
headers.add(col)
}
} else {//数据行
元素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 {
//?默认值
value =;
}

元素curElement = newDoc.createElement(header);
curElement.appendChild(newDoc.createTextNode(value));
rowElement.appendChild(curElement);
}
}
line ++;
}

ByteArrayOutputStream baos = null;
OutputStreamWriter osw = null;

try {
baos = new ByteArrayOutputStream();
osw = new OutputStreamWriter(baos);

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);

源src = new DOMSource(newDoc);
结果result = new StreamResult(osw);
aTransformer.transform(src,result);

osw.flush();
System.out.println(new String(baos.toByteArray()));
} catch(Exception exp){
exp.printStackTrace();
} finally {
try {
osw.close();
} catch(Exception e){
}
try {
baos.close();
} catch(Exception e){
}
}
} catch(Exception e){
e.printStackTrace
}

现在我使用了 List 而不是 Map 。你需要决定如何最好地处理缺失值问题。不提前知道文件的结构,这不是一个简单的解决方案。



无论如何,我最终得到

 <?xml version =1.0encoding =UTF-8standalone =no?> 
< XMLCreators>
< row>
< Name> chi< / Name>
< Age> 23< / Age>
< Sex />
< / row>
< row>
< Name> kay< / Name>
< Age> 19< / Age>
< Sex>男性< / Sex>
< / row>
< row>
< Name> John< / Name>
< Age> male< / Age>
< Sex />
< / row>
< / XMLCreators>

更新与合并

  public class XMLCreators {
//受保护的属性

protected DocumentBuilderFactory domFactory = null;
protected DocumentBuilder domBuilder = null;

public XMLCreators(){
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,
String delimiter){

int rowsCount = -1;
try {
Document newDoc = domBuilder.newDocument();
//根元素
元素rootElement = newDoc.createElement(XMLCreators);
newDoc.appendChild(rootElement);
//读取csv文件
BufferedReader csvReader;
csvReader = new BufferedReader(new FileReader(csvFileName));

// int fieldCount = 0;
// String [] csvFields = null;
// StringTokenizer stringTokenizer = null;
//
// //假设CSV文件中的第一行是列/字段名称
// //列名称用于命名XML文件中的元素,
// //避免使用空格或其他不适合XML元素的字符
// //命名
//
//字符串curLine = csvReader.readLine();
// if(curLine!= null){
// //其他形式的csv文件怎么样?
// stringTokenizer = new StringTokenizer(curLine,delimiter);
// fieldCount = stringTokenizer.countTokens();
// if(fieldCount> 0){
// csvFields = new String [fieldCount];
// int i = 0;
// while(stringTokenizer.hasMoreElements()){
// csvFields [i ++] = String.valueOf(stringTokenizer.nextElement());
//}
//}
//}
//
// //此时,coulmns是已知的,现在按行$ b读取数据$ b // while((curLine = csvReader.readLine())!= null){
// stringTokenizer = new StringTokenizer(curLine,delimiter);
// fieldCount = stringTokenizer.countTokens();
// if(fieldCount> 0){
//元素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();
//
// //将文档保存到磁盘文件
// TransformerFactory tranFactory = TransformerFactory.newInstance();
// Transformer aTransformer = tranFactory.newTransformer();
//源src = new DOMSource(newDoc);
//结果result = new StreamResult(new File(xmlFileName));
// aTransformer.transform(src,result);
// rowsCount ++;
int line = 0;
List< String> headers = new ArrayList< String>(5);

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

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

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

}

if(line == 0){//标题行

for(String col:rowValues){
headers .add(col);
}

} else {//数据行

rowsCount ++;

元素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 {
//?默认值
value =;
}

元素curElement = newDoc.createElement(header);
curElement.appendChild(newDoc.createTextNode(value));
rowElement.appendChild(curElement);

}

}
line ++;

}

ByteArrayOutputStream baos = null;
OutputStreamWriter osw = null;

try {

baos = new ByteArrayOutputStream();
osw = new OutputStreamWriter(baos);

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);

源src = new DOMSource(newDoc);
结果result = new StreamResult(osw);
aTransformer.transform(src,result);

osw.flush();
System.out.println(new String(baos.toByteArray()));

} catch(Exception exp){
exp.printStackTrace();
} finally {
try {
osw.close();
} catch(Exception e){
}
try {
baos.close();
} catch(Exception e){
}
}

//输出到控制台进行测试
// Resultt result = new StreamResult(System。 out);

} catch(IOException exp){
System.err.println(exp.toString());
} catch(Exception exp){
System.err.println(exp.toString());
}
return rowsCount;
//XLM文档已创建+ rowsCount;
}
}

使用OpenCSV更新

  public class XMLCreators {
//受保护的属性

protected DocumentBuilderFactory domFactory = null ;
protected DocumentBuilder domBuilder = null;

public XMLCreators(){
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,
String delimiter){

int rowsCount = -1;
BufferedReader csvReader;
try {
Document newDoc = domBuilder.newDocument();
//根元素
元素rootElement = newDoc.createElement(XMLCreators);
newDoc.appendChild(rootElement);
//读取csv文件
csvReader = new BufferedReader(new FileReader(csvFileName));

// **现在使用OpenCSV ** //
CSVReader reader = new CSVReader(new FileReader(names.csv),delimiter.charAt(0));
// CSVReader reader = new CSVReader(csvReader);
String [] nextLine;
int line = 0;
List< String> headers = new ArrayList< String>(5);
while((nextLine = reader.readNext())!= null){

if(line == 0){// Header row
for(String col:nextLine ){
headers.add(col);
}
} else {//数据行
元素rowElement = newDoc.createElement(row);
rootElement.appendChild(rowElement);

int col = 0;
for(String value:nextLine){
String header = headers.get(col);

元素curElement = newDoc.createElement(header);
curElement.appendChild(newDoc.createTextNode(value.trim()));
rowElement.appendChild(curElement);

col ++;
}
}
line ++;
}
// ** CSV解析结束** //

FileWriter writer = null;

try {

writer = new FileWriter(new File(xmlFileName));

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);

源src = new DOMSource(newDoc);
结果result = new StreamResult(writer);
aTransformer.transform(src,result);

writer.flush();

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

//输出到控制台进行测试
// Resultt result = new StreamResult(System。 out);

} catch(IOException exp){
System.err.println(exp.toString());
} catch(Exception exp){
System.err.println(exp.toString());
}
return rowsCount;
//XLM文档已创建+ rowsCount;
}
}


I have a set of CSV data to be converted to XML. The codes look OK but the output isn't perfect enough. It omits some columns because they have no value and produces a long line of XML data instead of breaking it.

This is a sample of my CSV data:

Name  Age Sex
chi   23   
kay   19  male
John      male

And my code:

public class XMLCreators {
  // Protected Properties
  protected DocumentBuilderFactory domFactory = null;
  protected DocumentBuilder domBuilder = null;

  public XMLCreators() {
    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,
      String delimiter) {

    int rowsCount = -1;
    try {
      Document newDoc = domBuilder.newDocument();
      // Root element
      Element rootElement = newDoc.createElement("XMLCreators");
      newDoc.appendChild(rootElement);
      // Read csv file
      BufferedReader csvReader;
      csvReader = new BufferedReader(new FileReader(csvFileName));
      int fieldCount = 0;
      String[] csvFields = null;
      StringTokenizer stringTokenizer = null;

      // Assumes the first line in CSV file is column/field names
      // The column names are used to name the elements in the XML file,
      // avoid the use of Space or other characters not suitable for XML element
      // naming

      String curLine = csvReader.readLine();
      if (curLine != null) {
        // how about other form of csv files?
        stringTokenizer = new StringTokenizer(curLine, delimiter);
        fieldCount = stringTokenizer.countTokens();
        if (fieldCount > 0) {
          csvFields = new String[fieldCount];
          int i = 0;
          while (stringTokenizer.hasMoreElements())
            csvFields[i++] = String.valueOf(stringTokenizer.nextElement());
        }
      }

      // At this point the coulmns are known, now read data by lines
      while ((curLine = csvReader.readLine()) != null) {
        stringTokenizer = new StringTokenizer(curLine, delimiter);
        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);
      Result result = new StreamResult(new File(xmlFileName));
      aTransformer.transform(src, result);
      rowsCount++;

      // Output to console for testing
      // Resultt result = new StreamResult(System.out);

    } catch (IOException exp) {
      System.err.println(exp.toString());
    } catch (Exception exp) {
      System.err.println(exp.toString());
    }
    return rowsCount;
    // "XLM Document has been created" + rowsCount;
  }
}

When this code is executed on the above data it produces:

<?xml version="1.0" encoding="UTF-8"?>
<XMLCreators>
<row>
<Name>chi</Name>
<Age>23</Age>
</row>
<row>
<Name>kay</Name>
<Age>19</Age>
<sex>male</sex>
</row>
<row>
<Name>john</Name>
<Age>male</Age>
</row>
</XMLCreators>

I arranged it in this form myself but the output produces a long line. The output to be produced should be:

<?xml version="1.0" encoding="UTF-8"?>
<XMLCreators>
<row>
<Name>chi</Name>
<Age>23</Age>
<sex></sex>
</row>
<row>
<Name>kay</Name>
<Age>19</Age>
<sex>male</sex>
</row>
<row>
<Name>john</Name>
<Age></Age>
<sex>male</sex>
 </row>
 </XMLCreators>

解决方案

I'd agree with Kennet.

I simply added

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

This added a new line between the elements and allowed for indentation.

UPDATED

Let's start with the fact that the file you're presented isn't a CSV (Comma separated value) file and I'll let you worry about that problem...

List<String> headers = new ArrayList<String>(5);

File file = new File("Names2.csv");
BufferedReader reader = null;

try {

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

    Document newDoc = domBuilder.newDocument();
    // Root element
    Element rootElement = newDoc.createElement("XMLCreators");
    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);
            }
        } 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 = "";
                }

                Element curElement = newDoc.createElement(header);
                curElement.appendChild(newDoc.createTextNode(value));
                rowElement.appendChild(curElement);
            }
        }
        line++;
    }

    ByteArrayOutputStream baos = null;
    OutputStreamWriter osw = null;

    try {
        baos = new ByteArrayOutputStream();
        osw = new OutputStreamWriter(baos);

        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(osw);
        aTransformer.transform(src, result);

        osw.flush();
        System.out.println(new String(baos.toByteArray()));
    } catch (Exception exp) {
        exp.printStackTrace();
    } finally {
        try {
            osw.close();
        } catch (Exception e) {
        }
        try {
            baos.close();
        } catch (Exception e) {
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}

Now I've used a List instead of a Map here. You'll need to decide how best to approach the missing values problem. Without knowing the structure of the file in advance, this is not going to be a simple solution.

Any way, I end up with

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<XMLCreators>
    <row>
        <Name>chi</Name>
        <Age>23</Age>
        <Sex/>
    </row>
    <row>
        <Name>kay</Name>
        <Age>19</Age>
        <Sex>male</Sex>
    </row>
    <row>
        <Name>John</Name>
        <Age>male</Age>
        <Sex/>
    </row>
</XMLCreators>

Updated with merge

public class XMLCreators {
    // Protected Properties

    protected DocumentBuilderFactory domFactory = null;
    protected DocumentBuilder domBuilder = null;

    public XMLCreators() {
        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,
                    String delimiter) {

        int rowsCount = -1;
        try {
            Document newDoc = domBuilder.newDocument();
            // Root element
            Element rootElement = newDoc.createElement("XMLCreators");
            newDoc.appendChild(rootElement);
            // Read csv file
            BufferedReader csvReader;
            csvReader = new BufferedReader(new FileReader(csvFileName));

//                int fieldCount = 0;
//                String[] csvFields = null;
//                StringTokenizer stringTokenizer = null;
//
//                // Assumes the first line in CSV file is column/field names
//                // The column names are used to name the elements in the XML file,
//                // avoid the use of Space or other characters not suitable for XML element
//                // naming
//
//                String curLine = csvReader.readLine();
//                if (curLine != null) {
//                    // how about other form of csv files?
//                    stringTokenizer = new StringTokenizer(curLine, delimiter);
//                    fieldCount = stringTokenizer.countTokens();
//                    if (fieldCount > 0) {
//                        csvFields = new String[fieldCount];
//                        int i = 0;
//                        while (stringTokenizer.hasMoreElements()) {
//                            csvFields[i++] = String.valueOf(stringTokenizer.nextElement());
//                        }
//                    }
//                }
//
//                // At this point the coulmns are known, now read data by lines
//                while ((curLine = csvReader.readLine()) != null) {
//                    stringTokenizer = new StringTokenizer(curLine, delimiter);
//                    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);
//                Result result = new StreamResult(new File(xmlFileName));
//                aTransformer.transform(src, result);
//                rowsCount++;
            int line = 0;
            List<String> headers = new ArrayList<String>(5);

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

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

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

                }

                if (line == 0) { // Header row

                    for (String col : rowValues) {
                        headers.add(col);
                    }

                } else { // Data row

                    rowsCount++;

                    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 = "";
                        }

                        Element curElement = newDoc.createElement(header);
                        curElement.appendChild(newDoc.createTextNode(value));
                        rowElement.appendChild(curElement);

                    }

                }
                line++;

            }

            ByteArrayOutputStream baos = null;
            OutputStreamWriter osw = null;

            try {

                baos = new ByteArrayOutputStream();
                osw = new OutputStreamWriter(baos);

                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(osw);
                aTransformer.transform(src, result);

                osw.flush();
                System.out.println(new String(baos.toByteArray()));

            } catch (Exception exp) {
                exp.printStackTrace();
            } finally {
                try {
                    osw.close();
                } catch (Exception e) {
                }
                try {
                    baos.close();
                } catch (Exception e) {
                }
            }

            // Output to console for testing
            // Resultt result = new StreamResult(System.out);

        } catch (IOException exp) {
            System.err.println(exp.toString());
        } catch (Exception exp) {
            System.err.println(exp.toString());
        }
        return rowsCount;
        // "XLM Document has been created" + rowsCount;
    }
}

UPDATED with use of OpenCSV

public class XMLCreators {
    // Protected Properties

    protected DocumentBuilderFactory domFactory = null;
    protected DocumentBuilder domBuilder = null;

    public XMLCreators() {
        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,
                    String delimiter) {

        int rowsCount = -1;
        BufferedReader csvReader;
        try {
            Document newDoc = domBuilder.newDocument();
            // Root element
            Element rootElement = newDoc.createElement("XMLCreators");
            newDoc.appendChild(rootElement);
            // Read csv file
            csvReader = new BufferedReader(new FileReader(csvFileName));

            //** Now using the OpenCSV **//
            CSVReader reader = new CSVReader(new FileReader("names.csv"), delimiter.charAt(0));
            //CSVReader reader = new CSVReader(csvReader);
            String[] nextLine;
            int line = 0;
            List<String> headers = new ArrayList<String>(5);
            while ((nextLine = reader.readNext()) != null) {

                if (line == 0) { // Header row
                    for (String col : nextLine) {
                        headers.add(col);
                    }
                } else { // Data row
                    Element rowElement = newDoc.createElement("row");
                    rootElement.appendChild(rowElement);

                    int col = 0;
                    for (String value : nextLine) {
                        String header = headers.get(col);

                        Element curElement = newDoc.createElement(header);
                        curElement.appendChild(newDoc.createTextNode(value.trim()));
                        rowElement.appendChild(curElement);

                        col++;
                    }
                }
                line++;
            }
            //** End of CSV parsing**//

            FileWriter writer = null;

            try {

                writer = new FileWriter(new File(xmlFileName));

                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(writer);
                aTransformer.transform(src, result);

                writer.flush();

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

            // Output to console for testing
            // Resultt result = new StreamResult(System.out);

        } catch (IOException exp) {
            System.err.println(exp.toString());
        } catch (Exception exp) {
            System.err.println(exp.toString());
        }
        return rowsCount;
        // "XLM Document has been created" + rowsCount;
    }
}

这篇关于使用JAVA将CSV转换为XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆