List of usage examples for javax.xml.transform.stream StreamResult StreamResult
public StreamResult(File f)
From source file:Main.java
public static void main(String[] args) throws Exception { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = db.parse(new InputSource(new StringReader("<root>\r\n" + // "<Users>\r\n" + // " <App id=\"test\">\r\n" + // " <Username>ADMIN</Username>\r\n" + // " <Password>ADMIN</Password>\r\n" + // " </App>\r\n" + // "</Users>\r\n" + // "<Users>\r\n" + // " <App id=\"test2\">\r\n" + // " <Username>ADMIN2</Username>\r\n" + // " <Password>ADMIN2</Password>\r\n" + // " </App>\r\n" + // "</Users>\r\n" + // "</root>"))); String inputId = "test2"; String xpathStr = "//Users/App[@id='" + inputId + "']"; // retrieve elements and change their content XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile(xpathStr + "/Username"); Node username = (Node) expr.evaluate(doc, XPathConstants.NODE); username.setTextContent("test-username"); expr = xpath.compile(xpathStr + "/Password"); Node password = (Node) expr.evaluate(doc, XPathConstants.NODE); password.setTextContent("test-password"); // output the document Transformer transformer = TransformerFactory.newInstance().newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); System.out.println(writer.toString()); }
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);// www.jav a 2 s.co 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(); }
From source file:Main.java
public static void main(String[] args) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); // Create a new document Document xmlDoc = builder.newDocument(); // Create root node for the document... Element root = xmlDoc.createElement("Players"); xmlDoc.appendChild(root);// w w w. j a va 2 s . c om // Create a "player" node Element player = xmlDoc.createElement("player"); // Set the players ID attribute player.setAttribute("ID", "1"); // Create currentRank node... Element currentRank = xmlDoc.createElement("currentRank"); currentRank.setTextContent("1"); player.appendChild(currentRank); // Create previousRank node... Element previousRank = xmlDoc.createElement("previousRank"); previousRank.setTextContent("1"); player.appendChild(previousRank); // Create playerName node... Element playerName = xmlDoc.createElement("PlayerName"); playerName.setTextContent("Max"); player.appendChild(playerName); // Create Money node... Element money = xmlDoc.createElement("Money"); money.setTextContent("15"); player.appendChild(money); // Add the player to the root node... root.appendChild(player); ByteArrayOutputStream baos = null; baos = new ByteArrayOutputStream(); Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.INDENT, "yes"); tf.setOutputProperty(OutputKeys.METHOD, "xml"); tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); DOMSource domSource = new DOMSource(xmlDoc); StreamResult sr = new StreamResult(baos); tf.transform(domSource, sr); baos.flush(); System.out.println(new String(baos.toByteArray())); baos.close(); }
From source file:SimpleTransform.java
public static void main(String[] args) throws TransformerException, TransformerConfigurationException, FileNotFoundException, IOException { // Use the static TransformerFactory.newInstance() method to instantiate // a TransformerFactory. The javax.xml.transform.TransformerFactory // system property setting determines the actual class to instantiate -- // org.apache.xalan.transformer.TransformerImpl. TransformerFactory tFactory = TransformerFactory.newInstance(); // Use the TransformerFactory to instantiate a Transformer that will work with // the stylesheet you specify. This method call also processes the stylesheet // into a compiled Templates object. Transformer transformer = tFactory.newTransformer(new StreamSource("birds.xsl")); // Use the Transformer to apply the associated Templates object to an XML document // (foo.xml) and write the output to a file (foo.out). transformer.transform(new StreamSource("birds.xml"), new StreamResult(new FileOutputStream("birds.out"))); System.out.println("************* The result is in birds.out *************"); }
From source file:Main.java
public static void main(String[] args) throws Exception { Main example = new Main(); example.data.put("France", "Paris"); example.data.put("Japan", "Tokyo"); JAXBContext context = JAXBContext.newInstance(Main.class); Marshaller marshaller = context.createMarshaller(); DOMResult result = new DOMResult(); marshaller.marshal(example, result); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); Document document = (Document) result.getNode(); XPathExpression expression = xpath.compile("//map/entry"); NodeList nodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET); expression = xpath.compile("//map"); Node oldMap = (Node) expression.evaluate(document, XPathConstants.NODE); Element newMap = document.createElement("map"); for (int index = 0; index < nodes.getLength(); index++) { Element element = (Element) nodes.item(index); newMap.setAttribute(element.getAttribute("key"), element.getAttribute("value")); }/*from www. ja v a2s. co m*/ expression = xpath.compile("//map/.."); Node parent = (Node) expression.evaluate(document, XPathConstants.NODE); parent.replaceChild(newMap, oldMap); TransformerFactory.newInstance().newTransformer().transform(new DOMSource(document), new StreamResult(System.out)); }
From source file:MainClass.java
public static void main(String[] args) throws Exception { SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); SOAPEnvelope soapEnvelope = soapPart.getEnvelope(); SOAPHeader soapHeader = soapEnvelope.getHeader(); SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12")); SOAPBody soapBody = soapEnvelope.getBody(); soapBody.addAttribute(/* w w w . j av a2s . c om*/ soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"), "Body"); Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com"); SOAPBodyElement gltp = soapBody.addBodyElement(bodyName); Source source = soapPart.getContent(); Node root = null; if (source instanceof DOMSource) { root = ((DOMSource) source).getNode(); } else if (source instanceof SAXSource) { InputSource inSource = ((SAXSource) source).getInputSource(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = null; db = dbf.newDocumentBuilder(); Document doc = db.parse(inSource); root = (Node) doc.getDocumentElement(); } Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(new DOMSource(root), new StreamResult(System.out)); }
From source file:com.l2jserver.model.template.SkillTemplateConverter.java
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException, JAXBException { Class.forName("com.mysql.jdbc.Driver"); final File target = new File("data/templates"); final JAXBContext c = JAXBContext.newInstance(SkillTemplate.class, LegacySkillList.class); final Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD); System.out.println("Generating template XML files..."); c.generateSchema(new SchemaOutputResolver() { @Override/*from ww w .j a v a 2 s . c om*/ public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException { return new StreamResult(new File(target, suggestedFileName)); } }); try { final Unmarshaller u = c.createUnmarshaller(); final Marshaller m = c.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "skill"); m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "skill ../skill.xsd"); Collection<File> files = FileUtils.listFiles(new File(LEGACY_SKILL_FOLDER), new String[] { "xml" }, true); for (final File legacyFile : files) { LegacySkillList list = (LegacySkillList) u.unmarshal(legacyFile); for (final LegacySkill legacySkill : list.skills) { SkillTemplate t = fillSkill(legacySkill); final File file = new File(target, "skill/" + t.id.getID() + (t.getName() != null ? "-" + camelCase(t.getName()) : "") + ".xml"); templates.add(t); try { m.marshal(t, getXMLSerializer(new FileOutputStream(file))); } catch (MarshalException e) { System.err.println( "Could not generate XML template file for " + t.getName() + " - " + t.getID()); file.delete(); } } } System.out.println("Generated " + templates.size() + " templates"); System.gc(); System.out.println("Free: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().freeMemory())); System.out.println("Total: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().totalMemory())); System.out.println("Used: " + FileUtils.byteCountToDisplaySize( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); System.out.println("Max: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().maxMemory())); } finally { conn.close(); } }
From source file:org.jasig.portlet.maps.tools.MapDataTransformer.java
/** * @param args//from w w w . ja v a 2s. c o m */ public static void main(String[] args) { // translate the KML file to the map portlet's native data format File kml = new File("map-data.xml"); File xslt = new File("google-earth.xsl"); try { TransformerFactory transFact = javax.xml.transform.TransformerFactory.newInstance(); Transformer trans = transFact.newTransformer(new StreamSource(xslt)); trans.transform(new StreamSource(kml), new StreamResult(System.out)); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } // deserialize the map data from XML MapData data = null; try { JAXBContext jc = JAXBContext.newInstance(MapData.class); Unmarshaller u = jc.createUnmarshaller(); data = (MapData) u.unmarshal(new FileInputStream(new File("map-data-transformed.xml"))); } catch (JAXBException e1) { e1.printStackTrace(); return; } catch (FileNotFoundException e) { e.printStackTrace(); return; } // ensure each location has a unique, non-null abbreviation setAbbreviations(data); // update each location with an address // setAddresses(data); // sort locations by name Collections.sort(data.getLocations(), new ByNameLocationComparator()); // serialize new map data out to a file into JSON format try { mapper.defaultPrettyPrintingWriter().writeValue(new File("map.json"), data); } catch (JsonGenerationException e) { System.out.println("Error generating JSON data for map"); e.printStackTrace(); } catch (JsonMappingException e) { System.out.println("Error generating JSON data for map"); e.printStackTrace(); } catch (IOException e) { System.out.println("Error writing JSON data to map file"); e.printStackTrace(); } }
From source file:JAXPTransletOneTransformation.java
public static void main(String argv[]) throws TransformerException, TransformerConfigurationException, IOException, SAXException, ParserConfigurationException, FileNotFoundException { // Set the TransformerFactory system property to generate and use a translet. // Note: To make this sample more flexible, load properties from a properties file. // The setting for the Xalan Transformer is "org.apache.xalan.processor.TransformerFactoryImpl" String key = "javax.xml.transform.TransformerFactory"; String value = "org.apache.xalan.xsltc.trax.TransformerFactoryImpl"; Properties props = System.getProperties(); props.put(key, value);//from w ww . j a v a 2s . c om System.setProperties(props); String xslInURI = "todo.xsl"; String xmlInURI = "todo.xml"; String htmlOutURI = "todo.html"; try { // Instantiate the TransformerFactory, and use it along with a SteamSource // XSL stylesheet to create a Transformer. TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new StreamSource(xslInURI)); // Perform the transformation from a StreamSource to a StreamResult; transformer.transform(new StreamSource(xmlInURI), new StreamResult(new FileOutputStream(htmlOutURI))); System.out.println("Produced todo.html"); } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); } }
From source file:net.fenyo.gnetwatch.Documentation.java
/** * General entry point./*from w ww.j a va2 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(); }