Sunday 31 July 2011

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

   
    
    
  

No comments:

Post a Comment