|
| 1 | +package ru.javaops.masterjava.xml.util; |
| 2 | + |
| 3 | +import javax.xml.transform.*; |
| 4 | +import javax.xml.transform.stream.StreamResult; |
| 5 | +import javax.xml.transform.stream.StreamSource; |
| 6 | +import java.io.*; |
| 7 | +import java.nio.charset.StandardCharsets; |
| 8 | + |
| 9 | +public class XsltProcessor { |
| 10 | + private static TransformerFactory FACTORY = TransformerFactory.newInstance(); |
| 11 | + private final Transformer xformer; |
| 12 | + |
| 13 | + public XsltProcessor(InputStream xslInputStream) { |
| 14 | + this(new BufferedReader(new InputStreamReader(xslInputStream, StandardCharsets.UTF_8))); |
| 15 | + } |
| 16 | + |
| 17 | + public XsltProcessor(Reader xslReader) { |
| 18 | + try { |
| 19 | + Templates template = FACTORY.newTemplates(new StreamSource(xslReader)); |
| 20 | + xformer = template.newTransformer(); |
| 21 | + } catch (TransformerConfigurationException e) { |
| 22 | + throw new IllegalStateException("XSLT transformer creation failed: " + e.toString(), e); |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + public String transform(InputStream xmlInputStream) throws TransformerException { |
| 27 | + StringWriter out = new StringWriter(); |
| 28 | + transform(xmlInputStream, out); |
| 29 | + return out.getBuffer().toString(); |
| 30 | + } |
| 31 | + |
| 32 | + public void transform(InputStream xmlInputStream, Writer result) throws TransformerException { |
| 33 | + transform(new BufferedReader(new InputStreamReader(xmlInputStream, StandardCharsets.UTF_8)), result); |
| 34 | + } |
| 35 | + |
| 36 | + public void transform(Reader sourceReader, Writer result) throws TransformerException { |
| 37 | + xformer.transform(new StreamSource(sourceReader), new StreamResult(result)); |
| 38 | + } |
| 39 | + |
| 40 | + public static String getXsltHeader(String xslt) { |
| 41 | + return "<?xml-stylesheet type=\"text/xsl\" href=\"" + xslt + "\"?>\n"; |
| 42 | + } |
| 43 | +} |
0 commit comments