我是Java的新手,并且一直在使用this教程将一个CSV文件转换为Mule ESB中的XML,使用的是使用Flatpack的Java类。这是我正在使用的输入文件:
Item1|Item2|Item3|Item4
Item5|Item6|Item7|Item8
这是我想要的输出:
<root>
<rows>
<a>Item1</a>
<b>Item2</b>
<c>Item3</c>
<d>Item4</d>
</rows>
<rows>
<a>Item5</a>
<b>Item6</b>
<c>Item7</c>
<d>Item8</d>
</rows>
</root>
我完全按照教程中给出的那样使用了Java脚本:
public class CsvConverter {
private static char delimiter = '|';
private static char qualifier = '"';
private static boolean ignoreFirstRecord = false;
public CsvConverter() {
}
public String convert(String csv) {
StringReader sr = new StringReader(csv);
FileReader fr = null;
//Get the configuration file for csv processing
try {
fr = new FileReader("src/main/resources/usermap.xml");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//The csv parser
Parser p = DefaultParserFactory.getInstance().newDelimitedParser(fr, sr,delimiter, qualifier, ignoreFirstRecord);
DefaultDataSet d = (DefaultDataSet) p.parse();
//Build the xml
DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
DocumentBuilder build;
Document doc=null;
try {
build = dFact.newDocumentBuilder();
doc = build.newDocument();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Element root = doc.createElement("root");
doc.appendChild(root);
Element Details = doc.createElement("rows");
root.appendChild(Details);
while (d.next()) {
String[] colums = d.getColumns();
for(int i=0; i<colums.length;i++ ){
Element name = doc.createElement(colums[i]);
name.appendChild(doc.createTextNode(d.getString(colums[i])));
Details.appendChild(name);
}
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer=null;
StringWriter writer = null;
try {
transformer = tf.newTransformer();
writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
String output = writer.getBuffer().toString();
return output;
}
}
这是usermap.xml
文件:
<?xml version="1.0"?>
<!DOCTYPE PZMAP SYSTEM "flatpack.dtd">
<PZMAP>
<COLUMN name="a"/>
<COLUMN name="b"/>
<COLUMN name="c"/>
<COLUMN name="d"/>
</PZMAP>
现在,我实际得到的输出看起来如下:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<rows>
<a>Item1</a>
<b>Item2</b>
<c>Item3</c>
<d>Item4</d>
<a>Item5</a>
<b>Item6</b>
<c>Item7</c>
<d>Item8</d>
</rows>
</root>
正如您所看到的那样,它不是将每行放在自己的<rows>
标记中,而是将所有行合并为一个<rows>
标记。我对Java知之甚少,到目前为止还无法诊断问题。是否有可能修改我在这里使用的Java脚本来创建我上面概述的所需输出?提前谢谢。
更新
根据@TheManzet提供的答案,通过一些实验,对while
循环进行了以下修改:
while (d.next()) {
Element Details = doc.createElement("rows");
String[] colums = d.getColumns();
for(int i=0; i<colums.length;i++ ){
Element name = doc.createElement(colums[i]);
name.appendChild(doc.createTextNode(d.getString(colums[i])));
Details.appendChild(name);
}
root.appendChild(Details);
}
答案 0 :(得分:1)
我目前无法测试,但我会尝试在root.appendChild(Details);
while (d.next()) {
现在你只添加一个rows元素,如果你为每一行添加它,它应该可以工作。