【发布时间】:2019-12-27 09:58:49
【问题描述】:
我开发了通过 xsl 将 xml 转换为 cvs 的应用程序。我使用了 DOM API,但它的性能很差(在输入中我有 100000 xml 大小 200kb-20mb)我尝试使用 SAX API,但我在转换后收到错误的结果输出。 DOM API:
@PostConstruct
public void init() throws ParserConfigurationException, TransformerConfigurationException {
styleSheet = new File("1.xsl");
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
stylesource = new StreamSource(styleSheet);
transformer = TransformerFactory.newInstance().newTransformer(stylesource);
}
public String transformXmlToCsv(String inputXml) {
String csv = null;
try {
InputSource is = new InputSource(new StringReader(inputXml));
Document document = builder.parse(is);
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
csv = writer.toString();
writer.close();
} catch (Exception e) {
LOGGER.error("Exception during transorming", e);
}
return csv;
}
}
SAX API:
public static void main(String[] args) throws Exception {
TransformerFactory transFact = TransformerFactory.newInstance( );
File xml = new File("019dc124-5057-43f3-aa5d-1d840536b1b5-1558467374000.xml");
File styleSheet = new File("1.xsl");
Result outputTarget = new StreamResult(new File("C:\\proj\\xmlparser\\result.csv"));
Source stylesource = new StreamSource(styleSheet);
Transformer trans = transFact.newTransformer(stylesource);
InputSource is = new InputSource(new FileReader(xml));
Source xmlSource = new SAXSource(is);
trans.transform(xmlSource, outputTarget);
}
【问题讨论】:
-
您需要准确解释问题所在,即第一个样本得到的结果以及第二个结果有何不同,以及您得到的任何确切错误。
-
@MartinHonnen 已编辑,成功运行没有错误
-
显示您的 XSL 文件。
-
@mentallurg 增加了 xsl 的短版本
-
很难从截图中看出哪里出了问题,但如果不需要的缩进/空白是问题,那么您通常可以使用例如修复它。
<xsl:text>Case</xsl:text>在模板中显式输出文字。