简体   繁体   English

使用Java将XML转换为CSV

[英]Convert XML to CSV with Java

i am trying to convert XML file into a CSV format with java and put the result in a new directory with the current date and hour as name. 我正在尝试使用java将XML文件转换为CSV格式,并将结果放入以当前日期和小时为名称的新目录中。 I am new in Java and until now i have just succeed to create the directory and do the conversion. 我是Java的新手,直到现在我还是成功创建了目录并进行了转换。 Can any one please tell me how i can do this correctly so that the converted file will automatically go into the created directory ? 谁能告诉我如何正确执行此操作,以便转换后的文件将自动进入创建的目录? Thank for your help. 谢谢您帮忙。 Here is the code i have used until now: 这是我到目前为止使用的代码:

    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);
    }
}

Change your AppDir variable value to point to the new directory created as follows: 更改您的AppDir变量值,使其指向创建的新目录,如下所示:

String AppDir = directory.getAbsolutePath() + File.seperator + XML + File.seperator;

In this way your all XML file will go inside newly created directory and then XML file directory. 这样,您的所有XML文件将进入新创建的目录,然后进入XML文件目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM