gpt4 book ai didi

java - javax.xml.transform.Source 的字符串操作

转载 作者:行者123 更新时间:2023-12-04 03:10:43 25 4
gpt4 key购买 nike

我正在使用 Java 和 XSL 样式表从 XML 文件中检索值并将其输出到文本文件。

下面是使用的程序:

    TransformerFactory factory = TransformerFactory.newInstance();
Source xslt = new StreamSource(new File("transform.xsl"));
Transformer transformer = factory.newTransformer(xslt);
Source text = new StreamSource(new File("inputXML.txt"));
transformer.transform(text, new StreamResult(new File("output.txt"))) ;

但最近我发现我要读取的 XML 文件将有 2 个根节点,而不是一个。所以我正在考虑进行字符串操作以编程方式添加我自己的根节点,这样我就可以避免以下错误:

ERROR: 'The markup in the document following the root element must be well-formed.' ERROR: 'com.sun.org.apache.xml.internal.utils.WrappedRuntimeException: The markup in the document following the root element must be well-formed.'

但我无法对 javax.xml.transform.Source 执行任何字符串操作(转换不工作)。我不想使用中间文件来添加我的根节点,因为我担心这会证明成本很高,因为我需要处理接近 50k 的 XML 记录。

最佳答案

StreamSource有几个构造函数

Path inputPath = Paths.get("inputXML.txt");
String input = new String(Files.readAllBytes(inputPath,
StandardCharsets.UTF_8));
input = input.replaceFirst("<quasiroot", "<root>$0")
+ "</root>";

Source text = new StreamSource(new StringReader(input));

关于java - javax.xml.transform.Source 的字符串操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45550827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com