Example usage for javax.xml.transform Transformer transform

List of usage examples for javax.xml.transform Transformer transform

Introduction

In this page you can find the example usage for javax.xml.transform Transformer transform.

Prototype

public abstract void transform(Source xmlSource, Result outputTarget) throws TransformerException;

Source Link

Document

Transform the XML Source to a Result.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    TransformerFactory factory = TransformerFactory.newInstance();
    Templates template = factory.newTemplates(new StreamSource(new FileInputStream("xsl.xlt")));
    Transformer xformer = template.newTransformer();
    Source source = new StreamSource(new FileInputStream("in.xml"));
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.newDocument();
    Result result = new DOMResult(doc);
    xformer.transform(source, result);
}

From source file:UseStylesheetParam.java

public static void main(String[] args)
        throws TransformerException, TransformerConfigurationException, SAXException, IOException {
    if (args.length != 1) {
        System.err.println("Please pass one string to this program");
        return;//from  ww w  . jav a2  s . co m
    }
    // Get the parameter value from the command line.
    String paramValue = args[0];

    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer(new StreamSource("foo.xsl"));

    // Set the parameter. I can't get non-null namespaces to work!!
    transformer.setParameter("param1", /* parameter name */
            paramValue /* parameter value */ );

    transformer.transform(new StreamSource("foo.xml"), new StreamResult(new OutputStreamWriter(System.out)));
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);//from   ww  w . j av a2  s.co m

    factory.setExpandEntityReferences(false);

    Document doc = factory.newDocumentBuilder().parse(new File("filename"));

    Transformer xformer = TransformerFactory.newInstance().newTransformer();

    xformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "publicId");
    xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "systemId");

    Source source = new DOMSource(doc);
    Result result = new StreamResult(new File("outfilename.xml"));
    xformer.transform(source, result);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    userdom = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element root = userdom.createElement("users");
    Node adoptNode = userdom.adoptNode(root);
    userdom.appendChild(adoptNode);/*  w  w  w  .  j a v  a2 s .com*/
    Element e = userdom.createElement("user");

    e.setAttribute("id", "blah");
    e.setAttribute("username", "kermit");
    e.setAttribute("password", "bunnies in the air");
    e.setAttribute("login", "kermmi");

    userdom.getFirstChild().appendChild(e);
    System.out.println(e);
    System.out.println(userdom.getFirstChild() + "|" + userdom.getFirstChild().getFirstChild());
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer trans = tf.newTransformer();
    System.out.println(userdom.getFirstChild() + "|" + userdom.getFirstChild().getFirstChild());
    DOMSource ds = new DOMSource(userdom);

    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        StreamResult sr = new StreamResult(baos);
        trans.transform(ds, sr);
        System.out.println(new String(baos.toByteArray()));
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    InputSource in = new InputSource(new FileInputStream("y.xml"));
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setNamespaceAware(true);//from ww w .j  a  va2 s  .  c  o  m
    Document doc = dfactory.newDocumentBuilder().parse(in);

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    CachedXPathAPI path = new CachedXPathAPI();
    NodeIterator nl = path.selectNodeIterator(doc, "\\abc\\");

    Node n;
    while ((n = nl.nextNode()) != null)
        transformer.transform(new DOMSource(n), new StreamResult(new OutputStreamWriter(System.out)));
}

From source file:Main.java

public static void main(String[] args) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = factory.newDocumentBuilder();
    Document xmlDoc = docBuilder.parse(new File("sample.xml"));
    NodeList nodes = xmlDoc.getElementsByTagName("fr");
    for (int i = 0, length = nodes.getLength(); i < length; i++) {
        ((Element) nodes.item(i)).setTextContent("Modified");
    }//from   ww  w . ja  v a  2  s.  c  o  m
    xmlDoc.getDocumentElement().normalize();
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    DOMSource domSource = new DOMSource(xmlDoc);
    StreamResult result = new StreamResult(new File("sample.xml"));
    transformer.transform(domSource, result);
    System.out.println("Modification Done");
}

From source file:Main.java

License:asdf

public static void main(String[] args) throws Exception {
    String initial = "<root><param value=\"abc\"/><param value=\"bc\"/></root>";
    ByteArrayInputStream is = new ByteArrayInputStream(initial.getBytes());
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(is);//from  w w  w.  j  av  a  2  s  . com

    // Create the new xml fragment
    Text a = doc.createTextNode("asdf");
    Node p = doc.createElement("parameterDesc");
    p.appendChild(a);
    Node i = doc.createElement("insert");
    i.appendChild(p);
    Element r = doc.getDocumentElement();
    r.insertBefore(i, r.getFirstChild());
    r.normalize();

    // Format the xml for output
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    // initialize StreamResult with File object to save to file
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);

    System.out.println(result.getWriter().toString());

}

From source file:Main.java

public static void main(String argv[]) throws Exception {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    // root elements
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("company");
    doc.appendChild(rootElement);/*from  w  w w  .  j a v a2 s  . com*/

    // staff elements
    Element staff = doc.createElement("Staff");
    rootElement.appendChild(staff);

    // set attribute to staff element
    Attr attr = doc.createAttribute("id");
    attr.setValue("1");
    staff.setAttributeNode(attr);

    // shorten way
    // staff.setAttribute("id", "1");

    // firstname elements
    Element firstname = doc.createElement("firstname");
    firstname.appendChild(doc.createTextNode("A"));
    staff.appendChild(firstname);

    // lastname elements
    Element lastname = doc.createElement("lastname");
    lastname.appendChild(doc.createTextNode("B"));
    staff.appendChild(lastname);

    // nickname elements
    Element nickname = doc.createElement("nickname");
    nickname.appendChild(doc.createTextNode("C"));
    staff.appendChild(nickname);

    // salary elements
    Element salary = doc.createElement("salary");
    salary.appendChild(doc.createTextNode("100000"));
    staff.appendChild(salary);

    // write the content into xml file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File("C:\\file.xml"));

    // Output to console for testing
    // StreamResult result = new StreamResult(System.out);

    transformer.transform(source, result);

    System.out.println("File saved!");
}

From source file:net.fenyo.gnetwatch.Documentation.java

/**
 * General entry point.//w  w  w.j  a va  2 s .c o m
 * @param args command line arguments.
 * @return void.
 * @throws IOException io exception.
 */
public static void main(String[] args) throws IOException, TransformerConfigurationException,
        TransformerException, FileNotFoundException, FOPException {
    final String docbook_stylesheets_path = args[0];

    // Get configuration properties.
    final Config config = new Config();

    // Read general logging rules.
    GenericTools.initLogEngine(config);
    log.info(config.getString("log_engine_initialized"));
    log.info(config.getString("begin"));

    Transformer docbookTransformerHTML = TransformerFactory.newInstance()
            .newTransformer(new StreamSource(new File(docbook_stylesheets_path + "/html/docbook.xsl")));
    //    docbookTransformerHTML.setParameter("draft.mode", "no");

    docbookTransformerHTML.transform(new StreamSource(new FileReader(new File("gnetwatch-documentation.xml"))),
            new StreamResult(new FileWriter(new File("c:/temp/gnetwatch-documentation.html"))));

    Transformer docbookTransformerFO = TransformerFactory.newInstance()
            .newTransformer(new StreamSource(new File(docbook_stylesheets_path + "/fo/docbook.xsl")));
    //    docbookTransformerFO.setParameter("draft.mode", "no");

    docbookTransformerFO.transform(new StreamSource(new FileReader(new File("gnetwatch-documentation.xml"))),
            new StreamResult(new FileWriter(new File("c:/temp/gnetwatch-documentation.fo"))));

    // for very old FOP version (0.20):
    //    Driver driver = new Driver();
    //    driver.setRenderer(Driver.RENDER_PDF);
    //    driver.setInputSource(new InputSource(new FileReader(new File("c:/temp/gnetwatch-documentation.fo"))));
    //    driver.setOutputStream(new FileOutputStream(new File("c:/temp/gnetwatch-documentation.pdf")));
    //    driver.run();
    // with new FOP version:
    OutputStream outStream = new BufferedOutputStream(
            new FileOutputStream("c:/temp/gnetwatch-documentation.pdf"));
    final FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
    Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outStream);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    Source source = new StreamSource(new FileReader(new File("c:/temp/gnetwatch-documentation.fo")));
    Result result = new SAXResult(fop.getDefaultHandler());
    transformer.transform(source, result);
    outStream.close();
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element results = doc.createElement("Results");
    doc.appendChild(results);//from  w  w  w  . java 2s . c o m

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager
            .getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/access.mdb");

    ResultSet rs = con.createStatement().executeQuery("select * from product");

    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    while (rs.next()) {
        Element row = doc.createElement("Row");
        results.appendChild(row);
        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnName(i);
            Object value = rs.getObject(i);
            Element node = doc.createElement(columnName);
            node.appendChild(doc.createTextNode(value.toString()));
            row.appendChild(node);
        }
    }
    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);
    transformer.transform(domSource, sr);

    System.out.println(sw.toString());

    con.close();
    rs.close();
}