Skip to content

Instantly share code, notes, and snippets.

@dazfuller
Created January 4, 2012 12:55
Show Gist options
  • Save dazfuller/1559935 to your computer and use it in GitHub Desktop.
Save dazfuller/1559935 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)
);
@KiranKumarGouda
Copy link

Please upload Total project for Eclipse .Because i'm not able to pass an arguments to transformXmlDocument method.
along with inputs XML and XSLT files.

Thanks in Advance!

@mailumes
Copy link

mailumes commented May 7, 2018

Everything good except image viewing problem. Please help. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment