我对 Java 非常陌生,并且一直在按照本教程使用使用 Flatpack 的 Java 类在 Mule ESB 中将 CSV 文件转换为 XML。这是我正在使用的输入文件:
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);
}