所以我需要将 CSV 文件转换为单独的 XML 文件(CSV 文件中每行一个 XML 文件)。这一切都很好,除了它拒绝添加一个值。它毫无问题地添加了另一个,但由于某种神秘的原因拒绝为我的一个节点创建标签。
Document newDoc = documentBuilder.newDocument();
Element rootElement = newDoc.createElement("XMLoutput");
newDoc.appendChild(rootElement);
String header = headers.get(col);
String value = null;
String value2 = null;
if (col < rowValues.length) {
if(header.equals("delay")) {
value = rowValues[col];
Thread.sleep(Long.parseLong(value));
}
Element shipidElement = newDoc.createElement("shipID");
shipidElement.appendChild(newDoc.createTextNode(FilenameUtils.getBaseName(csvFileName)));
rootElement.appendChild(shipidElement);
if(header.equals("centraleID")) {
value = rowValues[col];
System.out.println(value); //to check if the if condition works, it does
Element centralElement = newDoc.createElement(header);
Text child = newDoc.createTextNode(value);
centralElement.appendChild(child);
rootElement.appendChild(centralElement);
}
else if(header.equals("afstandTotKade")) {
value2 = rowValues[col];
Element curElement = newDoc.createElement(header);
curElement.appendChild(newDoc.createTextNode(value2));
rootElement.appendChild(curElement);
}
String timeStamp = new SimpleDateFormat("HH:mm:ss").format(new Date());
Element timeElement = newDoc.createElement("Timestamp");
timeElement.appendChild(newDoc.createTextNode(timeStamp));
rootElement.appendChild(timeElement);
}
所以在上面的代码中,CentraleID 的 if 循环检查实际上是有效的,因为它打印出值,但是 XML 文件没有添加标签,即使我只是插入一个字符串而不是标题值。但是,它确实插入了“afstandTotKade”节点和时间戳节点。我傻眼了。
PS:这当然只是部分代码,但是问题太小了,添加所有代码似乎是多余的。
PPS:代码和其他的一样,我只是在玩。
这是生成的 XML 文件顺便说一句,所以另一个 if 确实添加了节点,我知道在检查标题时拼写是正确的,因为它在我运行它时会打印出值(sout 代码):
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<XMLoutput>
<shipID>1546312</shipID>
<afstandTotKade>1000</afstandTotKade>
<Timestamp>22:06:33</Timestamp>
</XMLoutput>