首页 > 解决方案 > 如何通过目录循环 XSLT 转换?

问题描述

我正在使用 XSLT 转换一些 XML 文件。

这是我使用的脚本


import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;



public class XsltTransformer {
    public static void main(String[] args) throws IOException, URISyntaxException, TransformerException {
            String xmlFile = "/my/directory/file.xml"; //put path of input XML file between ""
            String xslFile = "/my/directory/file.xsl"; //put path of input XSL file between ""
            TransformerFactory factory = TransformerFactory.newInstance();
            Source xslt = new StreamSource(new File(xslFile));
            Transformer transformer = factory.newTransformer(xslt);
            Source text = new StreamSource(new File(xmlFile));
            transformer.transform(text, new StreamResult(new File("/my/directory/output.xml"))); //put path of newly created XML file between ""
    }
}

这样我就可以处理一个文件并且它可以工作。

但是,我需要扩展代码来处理遍历目录的多个 xml 文件。

结构是:

DirA
 |
 |-->SubDirA1
 |       |
 |       |---->XMLFile
 |
DirB
 |
 |-->SubDirB1
 |       |
 |       |---->XMLFile
 |
...

我认为这里已经部分回答了这个问题,但是我从未按照建议使用过 ant。

标签: javaxmlxslt

解决方案


您可以尝试遍历您的目录并处理将结果写入单独目录的每个文件。你通常Files.walk用于那个

import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import java.io.IOException;
import java.nio.file.*;

public class XsltTransformer {
    private final Path input;
    private final Path output;
    private final Transformer transformer;

    XsltTransformer(Path input, Path output, Transformer transformer) {
        this.input = input;this.output = output;this.transformer = transformer;
    }

    public static void main(String[] args) throws Exception {
        final Transformer transformer = TransformerFactory
            .newInstance()
            .newTransformer(new StreamSource(Paths.get("/my/directory/file.xsl").toFile()));
        new XsltTransformer(
            Paths.get("/my/directory"),
            Paths.get("/my/output"),
            transformer
        ).run();
    }

    private Path transform(Path file) {
        final StreamSource resource = new StreamSource(file.toFile());
        final Path output = this.resolveOutput(file);
        final Result result = new StreamResult(
            output.toFile()
        );
        try {
            this.transformer.transform(resource, result);
            return output;
        } catch (TransformerException ex) {
            throw new IllegalStateException(ex);
        }
    }

    private Path resolveOutput(Path file) {
        return this.output.resolve(this.input.relativize(file));
    }

    public void run() throws IOException {
        Files.walk(this.input)
            .filter(file -> file.getFileName().endsWith(".xml"))
            .map(this::transform)
            .forEach(System.out::println);
    }
}

推荐阅读