Java-将管道分隔的文本\csv文件转换为XML

Java-将管道分隔的文本\csv文件转换为XML,java,xml,Java,Xml,我想知道是否有一种公认的方法可以在Java中将管道分隔的文本文件转换为XML。我要转换的分隔文件的格式为: RefNo | Location | Name | Age 123 | North America | Steve | 32 我希望将其转换为: <data> <RefNo>123</RefNo> <location>North America</location>

我想知道是否有一种公认的方法可以在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>

123
北美
史蒂夫
32

以下是您问题的一些答案,但首先您应该用逗号替换管道分隔符,因为它是
CSV
XML

您可以使用
String
类中的
s.replaceAll(“|”),“,”
,并按照以下说明进行操作:


运行此处给出的XSLT转换,或根据需要进行调整:


我又找到了一种将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());
        }
    }
}
import java.io.*;
导入java.util.*;
导入org.w3c.dom.*;
导入javax.xml.parsers.*;
导入javax.xml.transform.*;
导入javax.xml.transform.dom.DOMSource;
导入javax.xml.transform.stream.StreamResult;
公共类CSV2XML{
//受保护财产
受保护的DocumentBuilderFactory domFactory=null;
受保护的DocumentBuilder domBuilder=null;
//执行器
公共CSV2XML()
{
尝试
{
domFactory=DocumentBuilderFactory.newInstance();
domBuilder=domFactory.newDocumentBuilder();
}
捕获(FactoryConfigurationError exp)
{
System.err.println(exp.toString());
}
捕获(ParserConfiguration异常扩展)
{
System.err.println(exp.toString());
}
捕获(异常扩展)
{
System.err.println(exp.toString());
}
}
public int convertFile(字符串csvFileName,字符串xmlFileName)
{
int rowsunt=-1;
尝试
{
Document newDoc=domguilder.newDocument();
//根元素
Element rootElement=newDoc.createElement(“CSV2XML”);
newDoc.appendChild(根元素);
//读取逗号分隔文件
缓冲读卡器csvReader;
csvFileName=“C:\\frnds.csv”;
csvReader=newbufferedreader(newfilereader(csvFileName));
int fieldCount=0;
字符串[]csvFields=null;
StringTokenizer StringTokenizer=null;
//假设:CSV文件的第一行是列/字段名
//由于列名用于命名XML文件中的元素,
//避免使用空格/任何其他不适合XML元素命名的字符
字符串curLine=csvReader.readLine();
如果(卷曲线!=null)
{
stringTokenizer=新的stringTokenizer(曲线,“,”);
fieldCount=stringTokenizer.countTokens();
如果(字段计数>0)
{
csvFields=新字符串[fieldCount];
int i=0;
while(stringTokenizer.hasMoreElements())
csvFields[i++]=
valueOf(stringTokenizer.nextElement());
}
}
//现在我们知道了列,现在让我们读取数据行
而((curLine=csvReader.readLine())!=null)
{
stringTokenizer=新的stringTokenizer(曲线,“,”);
fieldCount=stringTokenizer.countTokens();
如果(字段计数>0)
{
元素行元素=newDoc.createElement(“行”);
int i=0;
while(stringTokenizer.hasMoreElements())
{
尝试
{
字符串曲线值=
valueOf(stringTokenizer.nextElement());
元素元素=
createElement(csvFields[i++]);
appendChild(newDoc.createTextNode(CurveValue));
rowElement.appendChild(cureElement);
}
捕获(异常扩展)
{
}
}
appendChild(rowElement);
rowsCount++;
}
}
csvReader.close();
//将文档保存到磁盘文件
TransformerFactory transfactory=TransformerFactory.newInstance();
变压器变压器变压器=transfactory.newTransformer();
Source src=新DOMSource(新文档);
xmlFileName=“C:\\stest.xml”;
Result dest=newstreamresult(新文件(xmlFileName));
变换器(src,dest);
rowsCount++;
}
捕获(IOEXP异常)
{
System.err.println(exp.toString());
}
捕获(异常扩展)
{
System.err.println(exp.toString());
}
返回Rowsunt;
}
公共静态void main(字符串[]args)
{
尝试
{
args=新字符串[]{“C:\\frnds.csv”,“C:\\stest.xml”};
如果(参数长度!=2)
{
System.out.println(“用法:JavaCSV2xML”);
返回;
}
}
捕获(异常扩展)
{
System.err.println(exp.toString());
}
尝试
{
CSV2XML csvConverter=新的CSV2XML();
int rowscont=csvConverter.convertFile(args[0],args[1]);
如果(rowsCount>=0)
{
System.out.println(“CSV文件”'+args[0]+“'已成功转换为XML文件”'+args[1]+“'\n”+”(“+String.valueOf(rowsCount)+“rows”);
}
其他的
{
System.out.println(“将输入CSV文件''+args[0]+''转换为输出XML文件'+args[1]+''时出错”;
}
}
捕获(异常扩展)
{
System.err.println(exp.toString());
}
}
}