Skip to content

Instantly share code, notes, and snippets.

@jpukg
Forked from dazfuller/Data.java
Created October 1, 2016 21:11
Show Gist options
  • Save jpukg/a030cca4ceb751279a6f290fda9e5a23 to your computer and use it in GitHub Desktop.
Save jpukg/a030cca4ceb751279a6f290fda9e5a23 to your computer and use it in GitHub Desktop.
Method for transforming XML to XML using XSLT for Java/Android
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import android.util.Log;
public class Data {
public static final Document transformXmlDocument(Document sourceDocument, InputStream xsltFile) {
DOMSource xmlSource = new DOMSource(sourceDocument);
StreamSource xsltSource = new StreamSource(xsltFile);
Document transformedData = null;
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(xsltSource);
ByteArrayOutputStream output = new ByteArrayOutputStream();
StreamResult result = new StreamResult(output);
transformer.transform(xmlSource, result);
DocumentBuilder resultBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
transformedData = resultBuilder.parse(
new InputSource(
new StringReader(
new String(output.toByteArray())
)
)
);
} catch (Exception e) {
Log.e("XSLT Transformation", e.getMessage());
}
return transformedData;
}
}
Document filteredData = Data.transformXmlDocument(
myXmlDocument,
this.getResources().openRawResource(R.raw.xsltfile)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment