Java tutorial
//package com.java2s; import java.io.Reader; import java.io.StringReader; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Result; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Node; public class Main { public static Node trance(Node context, String xpath) throws Exception { Templates txp = TrAXPath(xpath); return trance(context, txp.newTransformer()); } public static Node trance(Node context, Transformer t) throws Exception { DocumentFragment df = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() .createDocumentFragment(); Result result = new DOMResult(df); t.transform(new DOMSource(context), result); return df; } public static Templates TrAXPath(String xpath) throws TransformerConfigurationException { StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); sb.append("<xsl:stylesheet version=\"1.0\" "); sb.append(" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">"); sb.append("<xsl:output method=\"xml\" indent=\"yes\"/>"); sb.append("<xsl:template match=\"" + xpath + "\">"); sb.append("<xsl:copy-of select=\".\"/>"); sb.append("</xsl:template>"); sb.append("<xsl:template match=\"*|@*|text()\">"); sb.append("<xsl:apply-templates />"); sb.append("</xsl:template>"); sb.append("</xsl:stylesheet>"); TransformerFactory tf = TransformerFactory.newInstance(); String stylesheet = sb.toString(); Reader r = new StringReader(stylesheet); StreamSource ssrc = new StreamSource(r); return tf.newTemplates(ssrc); } }