Gangmax Blog

My Tip 41

使用”Java XSLT”转换时,当”xslt”输出的内容不是”xml”而是”text”的时候,使用”DOMResult”接收”result”会导致结果为空,不是期待的内容。考虑使用”StreamResult”但是有异常,按照此文章解决:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
    public static void xsl(
String inFilename,
String outFilename,
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 FileInputStream(inFilename));
Result result = new StreamResult(new FileOutputStream(outFilename));

// Apply the xsl file to the source file and write the result to the
// output file
xformer.transform(source, result);
} catch (FileNotFoundException e) ...{
// File not found
} 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
}
}
}

Comments