我正在尝试制作一个带有2个参数的通用方法。 Xml作为String参数,Xsl文件的路径作为字符串参数。
该方法应返回一个字符串,其中xsl应用于xml,但它并没有真正做任何事情。
我猜这一行是错的: Source source = new StreamSource(new ByteArrayInputStream(xml.getBytes()));
因为当我尝试将其保存到磁盘而不是它工作正常 - 只是当我尝试将其全部存储在内存中时。
private static String Convert(String xml, String xslFilename ) {
try {
// Create transformer factory
TransformerFactory factory = TransformerFactory.newInstance();
// Use the factory to create a template containing the xsl file
Templates template = factory.newTemplates(new StreamSource(
new FileInputStream(xslFilename)));
// Use the template to create a transformer
Transformer xformer = template.newTransformer();
// Prepare the input and output files
Source source = new StreamSource(new ByteArrayInputStream(xml.getBytes()));
ByteArrayOutputStream output = new ByteArrayOutputStream();
Result result = new StreamResult(output);
// Apply the xsl file to the source file and write the result to the output file
xformer.transform(source, result);
String formattedResult = output.toString();
return formattedResult;
} catch (FileNotFoundException e) {
} catch (TransformerConfigurationException e) {
// An error occurred in the XSL file
} catch (TransformerException e) {
// An error occurred while applying the XSL file
// Get location of error in input file
SourceLocator locator = e.getLocator();
int col = locator.getColumnNumber();
int line = locator.getLineNumber();
String publicId = locator.getPublicId();
String systemId = locator.getSystemId();
}
return "";
}
}