Skip to content

Instantly share code, notes, and snippets.

@Crydust
Last active June 24, 2022 13:11
Show Gist options
  • Save Crydust/5137942 to your computer and use it in GitHub Desktop.
Save Crydust/5137942 to your computer and use it in GitHub Desktop.
transform xml with an xslt in java
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class TransformXml {
public static void main(String[] args) {
transformXml("style.xslt", "source.xml", "result.xml");
}
private static void transformXml(String xslt, String sourceXml, String resultXml) {
try {
System.out.format("xslt = %s, sourceXml = %s, resultXml = %s\n", xslt, sourceXml, resultXml);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource(xslt));
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
// (unnecessary) transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "4");
transformer.setOutputProperty("{http://saxon.sf.net/}indent-spaces", "4");
transformer.transform(new StreamSource(sourceXml), new StreamResult(new FileOutputStream(resultXml)));
} catch (Throwable t) {
t.printStackTrace();
}
}
public static void encodeXmlAsAscii(String sourceXml, String resultXml) {
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.ENCODING, "US-ASCII");
transformer.transform(new StreamSource(sourceXml), new StreamResult(new BufferedOutputStream(new FileOutputStream(resultXml))));
} catch (Throwable t) {
t.printStackTrace();
}
}
public static Document readXmlFromClassPath(String fileName) throws Exception {
try (InputStream in = TransformXml.class.getResourceAsStream(fileName);) {
return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
}
}
public static String xmlDocumentToString(Document doc) throws Exception {
StringWriter writer = new StringWriter();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(doc), new StreamResult(writer));
return writer.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment