[英]best way to read data from flat file and write it to xml
我有一个平面.txt文件,该文件中连续包含逗号分隔的值,例如:
1,name1,department1
2,name2,department2
3,name3,department3
...
...
现在,我想从.txt文件中读取这些记录并将其写入xml,并且输出应该类似于:
<Employees>
<Employee>
<Code>1</Code>
<Name>name1</Name>
<Department>department1</Department>
</Employee>
<Employee>
<Code>2</Code>
<Name>name2</Name>
<Department>department2</Department>
</Employee>
<Employee>
<Code>3</Code>
<Name>name3</Name>
<Department>department3</Department>
</Employee>
</Employees>
因此,现在要实现这一点,我遇到了各种各样的问题/帖子,以某种方式使我对应该遵循的方法以及应该使用哪种XMLBuilder(例如XStream)感到困惑。
谁能告诉我应该采取哪种方法才能获得最佳性能?
我将使用CSV库(例如openCSV)读取文件,然后使用JAXB创建XML文件。
您可以使用List<Employee>
创建一个Employees
类,其中Employee
包含Code
, Name
等字段。使用CSV库将其填写。 使用JAXB.marshal
方法之一将整个内容写到一行中。
简单的示例代码
@XmlRootElement
@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
public class XmlWriterTest
{
public String foo;
public List<String> bars;
public static void main(String[] args)
{
XmlWriterTest test = new XmlWriterTest();
test.foo = "hi";
test.bars = Arrays.asList("yo", "oi");
JAXB.marshal(test, System.out);
}
}
这是伪代码中最简单的方法:
file.write("<Employees>");
foreach(String line : file)
{
String[] parts = line.split(",");
file.write("<Employee><Code>" + parts[0] + "</Code><Name>" + parts[1] + "</Name><Department>" + parts[2] + "</Department></Employee>");
}
file.write("</Employees>");
显然,此解决方案非常幼稚,并假定您的平面文件在字段中不包含逗号,并且每一行正好有3列。
从您的评论来看,最简单的方法似乎就是不使用任何XML构建器使用print / write来执行此操作:
不要忘记XML标头。
如果您的格式经常更改,则可以编写一个.xsd schema
并使用jaxb
生成类层次结构并进行编组/解组代码,但是在这种情况下,这可能会显得过大。
一线awk解决方案怎么样?
awk -F, 'BEGIN{printf "<Employees>\n"}END{printf "</Employees>\n"}{printf"<Employee><Code>%s</Code><Name>%s</Name><Department>%s</Department></Employee>\n",$1,$2,$3}' data.txt
对于这样一个简单的问题,编写Java程序似乎显得过高。
如果要格式化输出,可以将其通过管道传递给xmllint命令:
$ awk -F, 'BEGIN{printf "<Employees>"}END{printf "</Employees>"}{printf"<Employee><Code>%s</Code><Name>%s</Name><Department>%s</Department></Employee>",$1,$2,$3}' data.txt | xmllint --format -
<?xml version="1.0"?>
<Employees>
<Employee>
<Code>1</Code>
<Name>name1</Name>
<Department>department1</Department>
</Employee>
<Employee>
<Code>2</Code>
<Name>name2</Name>
<Department>department2</Department>
</Employee>
<Employee>
<Code>3</Code>
<Name>name3</Name>
<Department>department3</Department>
</Employee>
</Employees>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.