java - 使用 Java 将 XML 转换为 CSV

标签 java xml xslt

我正在尝试使用 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/

相关文章:

xml - 编辑 SharePoint 2010 Rss Feed WebPart 的 XSL

java - 使用 fieldgroup 属性 vaadin 进行验证

java - float 类型转换无法正常工作,始终计算为 0.0

xml - 在配置 hadoop 时启动 yarn 服务时出现错误

java - JAX-WS @webMethod 手动反序列化

xml - 在xsl tokenize中,如何获取前面的文本值

c# - 为什么我会选择 XSLT 或 XQuery 而不是另一个来生成 html 文档?

java - 在mysql中将mysql日期格式转换为dd-mmm-yyyy

java - 在这种情况下,字符串构造函数 - String(String original) 中的 'size > originalValue.length' 会是 0x104567910 吗?

javascript - 通用库的 <svg> 的 setAttributeNS xmlns