Create an XML file and attach an XSL : Transform « XML « Java






Create an XML file and attach an XSL

      

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);
  }
}

   
    
    
    
    
    
  








Related examples in the same category

1.XML transformation
2.A Program That Performs XML Transformations
3.XSLT I18N
4.Use the transform.TransformerFactory plugability in the JAXP API
5.Processing XML Documents Partially
6.Set the TransformerFactory system property to generate and use translets
7.Transforming DOM Node to HTML with JAXP
8.Transformer with parameters
9.Applying XSLT Stylesheets
10.Catch TransformerException
11.Formatting an XML file using Transformer
12.Transforming an XML File with XSL into a DOM Document
13.XML input, output and transform utilities
14.XSL transformations: It applies a transformation to a set of employee recordsXSL transformations: It applies a transformation to a set of employee records
15.How to write an XML file. It saves a file describing a modern drawing in SVG format.
16.Applies a stylesheet to a given xml document.
17.Applies a stylesheet (that receives parameters) to a given xml document.
18.Apply some indentiation to some XML.