Create an XML file and attach an XSL : Transformer « XML « Java Tutorial






import javax.xml.parsers.DocumentBuilder;
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 org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Main {
  public static void main(String args[]) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    DOMImplementation impl = builder.getDOMImplementation();
    Document xmldoc = impl.createDocument(null, "XMLDoc", null);

    Element root = xmldoc.getDocumentElement();
    Element e0 = xmldoc.createElement("Doc");
    Element e1 = xmldoc.createElement("TITLE");
    Node n1 = xmldoc.createTextNode("Java");
    e1.appendChild(n1);

    Element e2 = xmldoc.createElement("data");
    Node n2 = xmldoc.createTextNode("text node");
    e2.appendChild(n2);

    e0.appendChild(e1);
    e0.appendChild(e2);
    root.appendChild(e0);

    StreamResult out = new StreamResult("howto.xml");
    DOMSource domSource = new DOMSource(xmldoc);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(domSource, out);
  }
}








33.11.Transformer
33.11.1.Source for the JAXP Transformation Application
33.11.2.Source for Transforming DOM Node to HTML with JAXP
33.11.3.Catch TransformerException
33.11.4.Transforming an XML File with XSL into a DOM Document
33.11.5.Applying XSLT Stylesheets
33.11.6.Create an XML file and attach an XSL
33.11.7.And now to attach an XSL
33.11.8.Formatting an XML file using Transformer