List of usage examples for javax.xml.transform TransformerFactory newInstance
public static TransformerFactory newInstance() throws TransformerFactoryConfigurationError
From source file:Main.java
public static void main(String[] args) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true);//w w w. j a v a 2s . c om DocumentBuilder db = dbf.newDocumentBuilder(); File file1 = new File("input1.xml"); Document doc1 = db.parse(file1); Element rootElement1 = doc1.getDocumentElement(); File file2 = new File("input2.xml"); Document doc2 = db.parse(file2); Element rootElement2 = doc2.getDocumentElement(); // Copy Child Nodes NodeList childNodes2 = rootElement2.getChildNodes(); for (int x = 0; x < childNodes2.getLength(); x++) { Node importedNode = doc1.importNode(childNodes2.item(x), true); if (importedNode.getNodeType() == Node.ELEMENT_NODE) { Element importedElement = (Element) importedNode; // Copy Attributes NamedNodeMap namedNodeMap2 = rootElement2.getAttributes(); for (int y = 0; y < namedNodeMap2.getLength(); y++) { Attr importedAttr = (Attr) doc1.importNode(namedNodeMap2.item(y), true); importedElement.setAttributeNodeNS(importedAttr); } } rootElement1.appendChild(importedNode); } // Output Document TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); DOMSource source = new DOMSource(doc1); StreamResult result = new StreamResult(System.out); t.transform(source, result); }
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 argv[]) throws Exception { String next = "keyword,123"; String[] input = next.split(","); String textToFind = input[0].replace("'", "\\'"); // "CEO"; String textToReplace = input[1].replace("'", "\\'"); // "Chief Executive Officer"; String filepath = "root.xml"; String fileToBeSaved = "root2.xml"; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(filepath); XPath xpath = XPathFactory.newInstance().newXPath(); // change ELEMENTS String xPathExpression = "//*[text()='" + textToFind + "']"; NodeList nodes = (NodeList) xpath.evaluate(xPathExpression, doc, XPathConstants.NODESET); for (int idx = 0; idx < nodes.getLength(); idx++) { nodes.item(idx).setTextContent(textToReplace); }// w w w .j a v a2 s .c o m // change ATTRIBUTES String xPathExpressionAttr = "//*/@*[.='" + textToFind + "']"; NodeList nodesAttr = (NodeList) xpath.evaluate(xPathExpressionAttr, doc, XPathConstants.NODESET); for (int i = 0; i < nodesAttr.getLength(); i++) { nodesAttr.item(i).setTextContent(textToReplace); } System.out.println("Everything replaced."); // save xml file back TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(fileToBeSaved)); transformer.transform(source, result); }
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 va 2s.c om*/ // 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: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 v a 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:Pipe.java
public static void main(String[] args) throws TransformerException, TransformerConfigurationException, SAXException, IOException { // Instantiate a TransformerFactory. TransformerFactory tFactory = TransformerFactory.newInstance(); // Determine whether the TransformerFactory supports The use uf SAXSource // and SAXResult if (tFactory.getFeature(SAXSource.FEATURE) && tFactory.getFeature(SAXResult.FEATURE)) { // Cast the TransformerFactory to SAXTransformerFactory. SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory); // Create a TransformerHandler for each stylesheet. TransformerHandler tHandler1 = saxTFactory.newTransformerHandler(new StreamSource("foo1.xsl")); TransformerHandler tHandler2 = saxTFactory.newTransformerHandler(new StreamSource("foo2.xsl")); TransformerHandler tHandler3 = saxTFactory.newTransformerHandler(new StreamSource("foo3.xsl")); // Create an XMLReader. XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(tHandler1); reader.setProperty("http://xml.org/sax/properties/lexical-handler", tHandler1); tHandler1.setResult(new SAXResult(tHandler2)); tHandler2.setResult(new SAXResult(tHandler3)); // transformer3 outputs SAX events to the serializer. java.util.Properties xmlProps = OutputPropertiesFactory.getDefaultMethodProperties("xml"); xmlProps.setProperty("indent", "yes"); xmlProps.setProperty("standalone", "no"); Serializer serializer = SerializerFactory.getSerializer(xmlProps); serializer.setOutputStream(System.out); tHandler3.setResult(new SAXResult(serializer.asContentHandler())); // Parse the XML input document. The input ContentHandler and output ContentHandler // work in separate threads to optimize performance. reader.parse("foo.xml"); }//from w ww. j a v a 2 s . co m }
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:UseXMLFilters.java
public static void main(String[] args) throws TransformerException, TransformerConfigurationException, SAXException, IOException { // Instantiate a TransformerFactory. TransformerFactory tFactory = TransformerFactory.newInstance(); // Determine whether the TransformerFactory supports The use uf SAXSource // and SAXResult if (tFactory.getFeature(SAXSource.FEATURE) && tFactory.getFeature(SAXResult.FEATURE)) { // Cast the TransformerFactory to SAXTransformerFactory. SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory); // Create an XMLFilter for each stylesheet. XMLFilter xmlFilter1 = saxTFactory.newXMLFilter(new StreamSource("foo1.xsl")); XMLFilter xmlFilter2 = saxTFactory.newXMLFilter(new StreamSource("foo2.xsl")); XMLFilter xmlFilter3 = saxTFactory.newXMLFilter(new StreamSource("foo3.xsl")); // Create an XMLReader. XMLReader reader = XMLReaderFactory.createXMLReader(); // xmlFilter1 uses the XMLReader as its reader. xmlFilter1.setParent(reader);//from ww w.j a va 2 s . com // xmlFilter2 uses xmlFilter1 as its reader. xmlFilter2.setParent(xmlFilter1); // xmlFilter3 uses xmlFilter2 as its reader. xmlFilter3.setParent(xmlFilter2); // xmlFilter3 outputs SAX events to the serializer. java.util.Properties xmlProps = OutputPropertiesFactory.getDefaultMethodProperties("xml"); xmlProps.setProperty("indent", "yes"); xmlProps.setProperty("standalone", "no"); Serializer serializer = SerializerFactory.getSerializer(xmlProps); serializer.setOutputStream(System.out); xmlFilter3.setContentHandler(serializer.asContentHandler()); // Perform the series of transformations as follows: // - transformer3 gets its parent (transformer2) as the XMLReader/XMLFilter // and calls transformer2.parse(new InputSource("foo.xml")). // - transformer2 gets its parent (transformer1) as the XMLReader/XMLFilter // and calls transformer1.parse(new InputSource("foo.xml")). // - transformer1 gets its parent (reader, a SAXParser) as the XMLReader // and calls reader.parse(new InputSource("foo.xml")). // - reader parses the XML document and sends the SAX parse events to transformer1, // which performs transformation 1 and sends the output to transformer2. // - transformer2 parses the transformation 1 output, performs transformation 2, and // sends the output to transformer3. // - transformer3 parses the transformation 2 output, performs transformation 3, // and sends the output to the serializer. xmlFilter3.parse(new InputSource("foo.xml")); } }
From source file:DOM2DOM.java
public static void main(String[] args) throws TransformerException, TransformerConfigurationException, FileNotFoundException, ParserConfigurationException, SAXException, IOException { TransformerFactory tFactory = TransformerFactory.newInstance(); if (tFactory.getFeature(DOMSource.FEATURE) && tFactory.getFeature(DOMResult.FEATURE)) { //Instantiate a DocumentBuilderFactory. DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance(); // And setNamespaceAware, which is required when parsing xsl files dFactory.setNamespaceAware(true); //Use the DocumentBuilderFactory to create a DocumentBuilder. DocumentBuilder dBuilder = dFactory.newDocumentBuilder(); //Use the DocumentBuilder to parse the XSL stylesheet. Document xslDoc = dBuilder.parse("birds.xsl"); // Use the DOM Document to define a DOMSource object. DOMSource xslDomSource = new DOMSource(xslDoc); // Set the systemId: note this is actually a URL, not a local filename xslDomSource.setSystemId("birds.xsl"); // Process the stylesheet DOMSource and generate a Transformer. Transformer transformer = tFactory.newTransformer(xslDomSource); //Use the DocumentBuilder to parse the XML input. Document xmlDoc = dBuilder.parse("birds.xml"); // Use the DOM Document to define a DOMSource object. DOMSource xmlDomSource = new DOMSource(xmlDoc); // Set the base URI for the DOMSource so any relative URIs it contains can // be resolved. xmlDomSource.setSystemId("birds.xml"); // Create an empty DOMResult for the Result. DOMResult domResult = new DOMResult(); // Perform the transformation, placing the output in the DOMResult. transformer.transform(xmlDomSource, domResult); //Instantiate an Xalan XML serializer and use it to serialize the output DOM to System.out // using the default output format, except for indent="yes" java.util.Properties xmlProps = OutputPropertiesFactory.getDefaultMethodProperties("xml"); xmlProps.setProperty("indent", "yes"); xmlProps.setProperty("standalone", "no"); Serializer serializer = SerializerFactory.getSerializer(xmlProps); serializer.setOutputStream(System.out); serializer.asDOMSerializer().serialize(domResult.getNode()); } else {/* ww w .jav a 2s. c o m*/ throw new org.xml.sax.SAXNotSupportedException("DOM node processing not supported!"); } }
From source file:SAX2SAX.java
public static void main(String[] args) throws TransformerException, TransformerConfigurationException, SAXException, IOException { // Instantiate a TransformerFactory. TransformerFactory tFactory = TransformerFactory.newInstance(); // Determine whether the TransformerFactory supports The use of SAXSource // and SAXResult if (tFactory.getFeature(SAXSource.FEATURE) && tFactory.getFeature(SAXResult.FEATURE)) { // Cast the TransformerFactory. SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory); // Create a ContentHandler to handle parsing of the stylesheet. TemplatesHandler templatesHandler = saxTFactory.newTemplatesHandler(); // Create an XMLReader and set its ContentHandler. XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(templatesHandler); // Parse the stylesheet. reader.parse("birds.xsl"); //Get the Templates object from the ContentHandler. Templates templates = templatesHandler.getTemplates(); // Create a ContentHandler to handle parsing of the XML source. TransformerHandler handler = saxTFactory.newTransformerHandler(templates); // Reset the XMLReader's ContentHandler. reader.setContentHandler(handler); // Set the ContentHandler to also function as a LexicalHandler, which // includes "lexical" events (e.g., comments and CDATA). reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); FileOutputStream fos = new FileOutputStream("birds.out"); java.util.Properties xmlProps = OutputPropertiesFactory.getDefaultMethodProperties("xml"); xmlProps.setProperty("indent", "yes"); xmlProps.setProperty("standalone", "no"); Serializer serializer = SerializerFactory.getSerializer(xmlProps); serializer.setOutputStream(fos); // Set the result handling to be a serialization to the file output stream. Result result = new SAXResult(serializer.asContentHandler()); handler.setResult(result);/* w w w . j ava 2 s.c o m*/ // Parse the XML input document. reader.parse("birds.xml"); System.out.println("************* The result is in birds.out *************"); } else System.out.println("The TransformerFactory does not support SAX input and SAX output"); }