我正在尝试使用 java 将 XML 文件转换为 CSV 格式,并将结果放入一个以当前日期和时间为名称的新目录中。我是 Java 新手,到目前为止我刚刚成功创建目录并进行转换。谁能告诉我如何正确执行此操作,以便转换后的文件将自动进入创建的目录?感谢您的帮助。 这是我到目前为止使用的代码:
public static void main(String args[]) throws Exception {
// Creating new directory in Java, if it doesn't exists
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
boolean success = false;
// String time = dateFormat.format(date);
String dir = "P:/export/";
File directory = new File(dir + dateFormat.format(date));
if (directory.exists()) {
System.out.println("Directory already exists ...");
}
else {
System.out.println("Directory not exists, creating now");
success = directory.mkdir();
directory.createNewFile();
if (success) {
System.out.printf("Successfully created new directory : %s%n", dir);
}
else {
System.out.printf("Failed to create new directory: %s%n", dir);
}
}
String AppDir = "P:/XML/";
File stylesheet = new File(AppDir + "xsl/newTest.xsl");
File xmlSource = new File(AppDir + "import/Tests/newTest.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlSource);
StreamSource stylesource = new StreamSource(stylesheet);
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(stylesource);
Source source = new DOMSource(document);
Result outputTarget = new StreamResult(new File(AppDir + "export/newTest.csv"));
transformer.transform(source, outputTarget);
}
}
最佳答案
更改您的 AppDir
变量值以指向创建的新目录,如下所示:
String AppDir = directory.getAbsolutePath() + File.seperator + XML + File.seperator;
这样您的所有 XML 文件将进入新创建的目录,然后是 XML 文件目录。
关于java - 使用 Java 将 XML 转换为 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41017500/