[英]Convert XML to CSV with Java
我正在嘗試使用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文件目錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.