Mar 10

Transforming XML in Java is achieved using a Transformer. To use an XSL file for the transformation involves first creating Templates instance which can then be used to create the required Transformer.

TransformerFactory factory = TransformerFactory.newInstance();
Templates template = factory.newTemplates(
   new StreamSource(new FileInputStream(xslPath)));
Transformer transformer = template.newTransformer();
Source source = new StreamSource(new FileInputStream(xmlInputPath));
Result result = new StreamResult(new FileOutputStream(xmlOutputPath));
transformer.transform(source, result);

written by objects \\ tags: , , ,

Mar 10

A Transformer can be used to write the XML for a DOM Document to a String. As the name implies a Transformer transforms a Source object into a Result, in this case the Source is the DOM Document, and the Result is a StringWriter (which the resulting XML String can be extracted from).

TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
StringWriter writer = new StringWriter();
Result result = new StreamResult(writer);
Source source = new DOMSource(document);
transformer.transform(source, result);
writer.close();
String xml = writer.toString();

written by objects \\ tags: , , ,

Feb 10

A Transformer can be used to write a the XML for a DOM Document to a file. As the name implies a Transformer transforms a Source object into a Result, in this case the Source is the DOM Document, and the Result is an XML file.

TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
Result result = new StreamResult(new File(xmlOutputFilePath));
Source source = new DOMSource(document);
transformer.transform(source, result);

written by objects \\ tags: , ,