java - 如何通过目录循环 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。
解决方案
您可以尝试遍历您的目录并处理将结果写入单独目录的每个文件。你通常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);
}
}
推荐阅读
- java - 如何将外部库添加到 android studio?如果能够添加。如果有更改,我如何更新外部库?
- javascript - 在 Node.js 中等待来自子进程的流输入
- kotlin - 我应该为来自依赖注入的函数参数添加@Inject 吗?
- node.js - 使用 Sequelize 从多个表中获取数据
- python - 如何使图像出现在一个地方,然后多次出现在另一个位置?
- java - 在 Camel Route 中为 JSON 对象添加引号
- python - DataFrame 类型的对象不是 JSON 可序列化的
- javascript - 异步加载 JS
- java - 蒙特卡洛树搜索未能做出最佳移动
- node.js - NODEJS Google Admin Api 错误:缺少原生承诺,请将 fetch.Promise 设置为您最喜欢的替代方案