List of usage examples for javax.xml.transform OutputKeys ENCODING
String ENCODING
To view the source code for javax.xml.transform OutputKeys ENCODING.
Click Source Link
From source file:com.haulmont.cuba.restapi.XMLConverter.java
protected String documentToString(Document document) { try {/*from w w w . j a v a 2 s .co m*/ Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name()); transformer.setOutputProperty(OutputKeys.STANDALONE, "no"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.INDENT, "no"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StringWriter sw = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(sw)); return sw.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:de.betterform.xml.dom.DOMUtil.java
public static void prettyPrintDOMAsHTML(Node node, OutputStream stream) throws TransformerException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "html"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(new DOMSource(node), new StreamResult(stream)); }
From source file:com.diversityarrays.dalclient.DalUtil.java
public static void writeXmlResult(String xml, Writer w) throws IOException, TransformerException { StreamSource source = new StreamSource(new StringReader(xml)); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.ENCODING, ENCODING_UTF_8); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$ transformer.transform(source, new StreamResult(w)); }
From source file:main.java.vasolsim.common.file.__NONUSEDREFERENCE_VaSOLSimExam.java
/** * Writes a digitized version of the VaSOLSim test, represented by an thisInstance of this class, * to a given file in//from w ww. j ava 2s. com * XML format. Prior to writing, this function will (re)initialize teh Ciphers used to protect the file, and update * all protected information accordingly. * * @param simFile the file on the disk to be written * @param canOverwriteFile can this method call write over an existing file with content * * @return if the write operation was successful * * @throws VaSolSimException thrown if insufficient information to write the file is contained in VaSolSimTest * object. Please ensure a password is provided to protect answer data and potentially * email data if test statistics and notifications are reported. */ public boolean write(File simFile, boolean canOverwriteFile) throws VaSolSimException { if (simFile.isFile()) { if (!canOverwriteFile) { throw new VaSolSimException(ERROR_MESSAGE_FILE_ALREADY_EXISTS); } else { PrintWriter printWriter; try { printWriter = new PrintWriter(simFile); } catch (FileNotFoundException e) { throw new VaSolSimException(ERROR_MESSAGE_FILE_NOT_FOUND_AFTER_INTERNAL_CHECK); } printWriter.print(""); printWriter.close(); } } else { if (!simFile.getParentFile().isDirectory() && !simFile.getParentFile().mkdirs()) { throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_DIRS); } try { if (!simFile.createNewFile()) { throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_FILE); } } catch (IOException e) { throw new VaSolSimException(ERROR_MESSAGE_CREATE_FILE_EXCEPTION); } } //update crypto stuff updateCryptoEngine(); updateCryptoProperties(); /* * Check for any missing encrypted data that is required to read the test as specified */ if (encryptedValidationHash.length < 1) throw new VaSolSimException(ERROR_MESSAGE_VALIDATION_KEY_NOT_PROVIDED); /* * Leave out for client side information gathering */ /* if (isNotifyingCompletion && encryptedNotificationEmail.length < 1) throw new VaSolSimException("Notification requested with no email provided!"); */ if (isNotifyingCompletion && isNotifyingCompletionUsingStandaloneEmailParadigm && encryptedNotificationEmailPassword.length < 1) throw new VaSolSimException(ERROR_MESSAGE_STANDALONE_NOTIFICATION_PASSWORD_NOT_PROVIDED); /* if (isReportingStatistics && encryptedStatisticsEmail.length < 1) throw new VaSolSimException("Statistics requested with no email provided!"); */ if (isReportingStatistics && isReportingStatisticsUsingStandaloneEmailParadigm && encryptedStatisticsEmailPassword.length < 1) throw new VaSolSimException(ERROR_MESSAGE_STANDALONE_STATS_PASSWORD_NOT_PROVIDED); Document solExam; try { solExam = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); } catch (ParserConfigurationException e) { throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_XML_PARSER_INITIALIZATION_EXCEPTION, e); } //create document root Element root = solExam.createElement(xmlRootElementName); solExam.appendChild(root); //append the information sub element Element information = solExam.createElement(xmlInfoElementName); root.appendChild(information); Element security = solExam.createElement(xmlSecurityElementName); root.appendChild(security); /* * Build information element tree */ createInformationElements(information, solExam); /* * Build security element tree */ createSecurityElements(security, solExam); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd"); transformer.setOutputProperty(indentationKey, "4"); transformer.transform(new DOMSource(solExam), new StreamResult(new FileOutputStream(simFile))); } catch (FileNotFoundException e) { throw new VaSolSimException(ERROR_MESSAGE_FILE_NOT_FOUND_AFTER_INTERNAL_CHECK, e); } catch (TransformerConfigurationException e) { throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_TRANSFORMER_CONFIGURATION, e); } catch (TransformerException e) { throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_TRANSFORMER_EXCEPTION, e); } return true; }
From source file:vmTools.java
public String createVmXml(String jsonString, String server) { String ret = ""; ArrayList<String> ide = new ArrayList<String>(); ide.add("hda"); ide.add("hdb"); ide.add("hdc"); ide.add("hdd"); ide.add("hde"); ide.add("hdf"); ArrayList<String> scsi = new ArrayList<String>(); scsi.add("sda"); scsi.add("sdb"); scsi.add("sdc"); scsi.add("sdd"); scsi.add("sde"); scsi.add("sdf"); try {// w w w. j av a2 s .com JSONObject jo = new JSONObject(jsonString); // A JSONArray is an ordered sequence of values. Its external form is a // string wrapped in square brackets with commas between the values. // Get the JSONObject value associated with the search result key. String varName = jo.get("name").toString(); String domainType = jo.get("domain_type").toString(); String varMem = jo.get("memory").toString(); String varCpu = jo.get("vcpu").toString(); String varArch = jo.get("arch").toString(); // Get the JSONArray value associated with the Result key JSONArray diskArray = jo.getJSONArray("diskList"); JSONArray nicArray = jo.getJSONArray("nicList"); // Cration d'un nouveau DOM DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance(); DocumentBuilder constructeur = fabrique.newDocumentBuilder(); Document document = constructeur.newDocument(); // Proprits du DOM document.setXmlStandalone(true); // Cration de l'arborescence du DOM Element domain = document.createElement("domain"); document.appendChild(domain); domain.setAttribute("type", domainType); //racine.appendChild(document.createComment("Commentaire sous la racine")); Element name = document.createElement("name"); domain.appendChild(name); name.setTextContent(varName); UUID varuid = UUID.randomUUID(); Element uid = document.createElement("uuid"); domain.appendChild(uid); uid.setTextContent(varuid.toString()); Element memory = document.createElement("memory"); domain.appendChild(memory); memory.setTextContent(varMem); Element currentMemory = document.createElement("currentMemory"); domain.appendChild(currentMemory); currentMemory.setTextContent(varMem); Element vcpu = document.createElement("vcpu"); domain.appendChild(vcpu); vcpu.setTextContent(varCpu); //<os> Element os = document.createElement("os"); domain.appendChild(os); Element type = document.createElement("type"); os.appendChild(type); type.setAttribute("arch", varArch); type.setAttribute("machine", jo.get("machine").toString()); type.setTextContent(jo.get("machine_type").toString()); JSONArray bootArray = jo.getJSONArray("bootList"); int count = bootArray.length(); for (int i = 0; i < count; i++) { JSONObject bootDev = bootArray.getJSONObject(i); Element boot = document.createElement("boot"); os.appendChild(boot); boot.setAttribute("dev", bootDev.get("dev").toString()); } Element bootmenu = document.createElement("bootmenu"); os.appendChild(bootmenu); bootmenu.setAttribute("enable", jo.get("bootMenu").toString()); //</os> //<features> Element features = document.createElement("features"); domain.appendChild(features); JSONArray featureArray = jo.getJSONArray("features"); int featureCount = featureArray.length(); for (int i = 0; i < featureCount; i++) { JSONObject jasonFeature = featureArray.getJSONObject(i); String newFeature = jasonFeature.get("opt").toString(); Element elFeature = document.createElement(newFeature); features.appendChild(elFeature); } //</features> Element clock = document.createElement("clock"); domain.appendChild(clock); // Clock settings clock.setAttribute("offset", jo.get("clock_offset").toString()); JSONArray timerArray = jo.getJSONArray("timers"); for (int i = 0; i < timerArray.length(); i++) { JSONObject jsonTimer = timerArray.getJSONObject(i); Element elTimer = document.createElement("timer"); clock.appendChild(elTimer); elTimer.setAttribute("name", jsonTimer.get("name").toString()); elTimer.setAttribute("present", jsonTimer.get("present").toString()); elTimer.setAttribute("tickpolicy", jsonTimer.get("tickpolicy").toString()); } Element poweroff = document.createElement("on_poweroff"); domain.appendChild(poweroff); poweroff.setTextContent(jo.get("on_poweroff").toString()); Element reboot = document.createElement("on_reboot"); domain.appendChild(reboot); reboot.setTextContent(jo.get("on_reboot").toString()); Element crash = document.createElement("on_crash"); domain.appendChild(crash); crash.setTextContent(jo.get("on_crash").toString()); //<devices> Element devices = document.createElement("devices"); domain.appendChild(devices); String varEmulator = jo.get("emulator").toString(); Element emulator = document.createElement("emulator"); devices.appendChild(emulator); emulator.setTextContent(varEmulator); int resultCount = diskArray.length(); for (int i = 0; i < resultCount; i++) { Element disk = document.createElement("disk"); devices.appendChild(disk); JSONObject newDisk = diskArray.getJSONObject(i); String diskType = newDisk.get("type").toString(); Element driver = document.createElement("driver"); Element target = document.createElement("target"); disk.appendChild(driver); disk.appendChild(target); if (diskType.equals("file")) { Element source = document.createElement("source"); disk.appendChild(source); source.setAttribute("file", newDisk.get("source").toString()); driver.setAttribute("cache", "none"); } disk.setAttribute("type", diskType); disk.setAttribute("device", newDisk.get("device").toString()); driver.setAttribute("type", newDisk.get("format").toString()); driver.setAttribute("name", newDisk.get("driver").toString()); //String diskDev = ide.get(0); //ide.remove(0); String diskDev = newDisk.get("bus").toString(); String diskBus = ""; if (diskDev.indexOf("hd") > -1) { diskBus = "ide"; } else if (diskDev.indexOf("sd") > -1) { diskBus = "scsi"; } else if (diskDev.indexOf("vd") > -1) { diskBus = "virtio"; } target.setAttribute("dev", diskDev); target.setAttribute("bus", diskBus); } resultCount = nicArray.length(); for (int i = 0; i < resultCount; i++) { JSONObject newNic = nicArray.getJSONObject(i); String macaddr = newNic.get("mac").toString().toLowerCase(); if (macaddr.indexOf("automatic") > -1) { Random rand = new Random(); macaddr = "52:54:00"; String hexa = Integer.toHexString(rand.nextInt(255)); macaddr += ":" + hexa; hexa = Integer.toHexString(rand.nextInt(255)); macaddr += ":" + hexa; hexa = Integer.toHexString(rand.nextInt(255)); macaddr += ":" + hexa; } Element netIf = document.createElement("interface"); devices.appendChild(netIf); Element netSource = document.createElement("source"); Element netDevice = document.createElement("model"); Element netMac = document.createElement("mac"); netIf.appendChild(netSource); netIf.appendChild(netDevice); netIf.appendChild(netMac); netIf.setAttribute("type", "network"); netSource.setAttribute("network", newNic.get("bridge").toString()); String portgroup = newNic.get("portgroup").toString(); if (!portgroup.equals("")) { netSource.setAttribute("portgroup", portgroup); } netDevice.setAttribute("type", newNic.get("device").toString()); netMac.setAttribute("address", macaddr); } JSONArray serialArray = jo.getJSONArray("serial"); count = serialArray.length(); for (int i = 0; i < count; i++) { JSONObject serialDev = serialArray.getJSONObject(i); Element serial = document.createElement("serial"); devices.appendChild(serial); serial.setAttribute("type", serialDev.get("type").toString()); Element target = document.createElement("target"); serial.appendChild(target); target.setAttribute("port", serialDev.get("port").toString()); } JSONArray consoleArray = jo.getJSONArray("console"); count = consoleArray.length(); for (int i = 0; i < count; i++) { JSONObject consoleDev = consoleArray.getJSONObject(i); Element console = document.createElement("console"); devices.appendChild(console); console.setAttribute("type", "pty"); Element target = document.createElement("target"); console.appendChild(target); target.setAttribute("port", consoleDev.get("port").toString()); target.setAttribute("type", consoleDev.get("type").toString()); } JSONArray inputArray = jo.getJSONArray("input"); count = inputArray.length(); for (int i = 0; i < count; i++) { JSONObject inputDev = inputArray.getJSONObject(i); Element input = document.createElement("input"); devices.appendChild(input); input.setAttribute("type", inputDev.get("type").toString()); input.setAttribute("bus", inputDev.get("bus").toString()); } JSONArray graphicsArray = jo.getJSONArray("graphics"); count = graphicsArray.length(); for (int i = 0; i < count; i++) { JSONObject graphicsDev = graphicsArray.getJSONObject(i); Element graphics = document.createElement("graphics"); devices.appendChild(graphics); graphics.setAttribute("type", graphicsDev.get("type").toString()); graphics.setAttribute("port", graphicsDev.get("port").toString()); graphics.setAttribute("autoport", graphicsDev.get("autoport").toString()); graphics.setAttribute("listen", graphicsDev.get("listen").toString()); graphics.setAttribute("keymap", graphicsDev.get("keymap").toString()); } JSONArray soundArray = jo.getJSONArray("sound"); count = soundArray.length(); for (int i = 0; i < count; i++) { JSONObject soundDev = soundArray.getJSONObject(i); Element sound = document.createElement("sound"); devices.appendChild(sound); sound.setAttribute("model", soundDev.get("model").toString()); } //sound.setAttribute("model", "ac97"); JSONArray videoArray = jo.getJSONArray("video"); count = videoArray.length(); for (int i = 0; i < count; i++) { JSONObject videoDev = videoArray.getJSONObject(i); Element video = document.createElement("video"); devices.appendChild(video); Element model = document.createElement("model"); video.appendChild(model); model.setAttribute("model", videoDev.get("type").toString()); model.setAttribute("model", videoDev.get("vram").toString()); model.setAttribute("model", videoDev.get("heads").toString()); } //write the content into xml file this.makeRelativeDirs("/" + server + "/vm/configs/" + varName); String pathToXml = RuntimeAccess.getInstance().getSession().getServletContext() .getRealPath("resources/data/" + server + "/vm/configs/" + varName + "/" + varName + ".xml"); File xmlOutput = new File(pathToXml); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(xmlOutput); transformer.transform(source, result); StringWriter stw = new StringWriter(); transformer.transform(source, new StreamResult(stw)); ret = stw.toString(); } catch (Exception e) { log(ERROR, "create xml file has failed", e); return e.toString(); } return ret; }
From source file:com.diversityarrays.dalclient.DalUtil.java
public static void printXmlDocument(Document doc, Writer w) throws IOException, TransformerException { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.ENCODING, ENCODING_UTF_8); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); //$NON-NLS-1$ //$NON-NLS-2$ transformer.transform(new DOMSource(doc), new StreamResult(w)); }
From source file:elh.eus.absa.CorpusReader.java
/** * print annotations in Semeval-absa 2015 format * * @param savePath string : path for the file to save the data * @throws ParserConfigurationException/*from w ww . jav a 2 s.c o m*/ */ public void print2Semeval2015format(String savePath) throws ParserConfigurationException { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements org.w3c.dom.Document doc = docBuilder.newDocument(); org.w3c.dom.Element rootElement = doc.createElement("Reviews"); doc.appendChild(rootElement); for (String rev : getReviews().keySet()) { // review elements org.w3c.dom.Element review = doc.createElement("Review"); rootElement.appendChild(review); // set id attribute to sentence element review.setAttribute("rid", rev); // Sentences element org.w3c.dom.Element sentences = doc.createElement("sentences"); review.appendChild(sentences); List<String> processed = new ArrayList<String>(); for (String sent : this.revSents.get(rev)) { if (processed.contains(sent)) { continue; } else { processed.add(sent); } //System.err.println("creating elements for sentence "+sent); // sentence elements org.w3c.dom.Element sentence = doc.createElement("sentence"); sentences.appendChild(sentence); // set attribute to sentence element sentence.setAttribute("id", sent); // text element of the current sentence org.w3c.dom.Element text = doc.createElement("text"); sentence.appendChild(text); text.setTextContent(getSentences().get(sent)); // Opinions element org.w3c.dom.Element opinions = doc.createElement("Opinions"); sentence.appendChild(opinions); for (Opinion op : getSentenceOpinions(sent)) { if (op.getCategory().equalsIgnoreCase("NULL")) { continue; } // opinion elements org.w3c.dom.Element opinion = doc.createElement("Opinion"); opinions.appendChild(opinion); // set attributes to the opinion element opinion.setAttribute("target", op.getTarget()); opinion.setAttribute("category", op.getCategory()); opinion.setAttribute("polarity", op.getPolarity()); opinion.setAttribute("from", op.getFrom().toString()); opinion.setAttribute("to", op.getTo().toString()); } } } // write the content into xml file try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(savePath)); // Output to console for testing //StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.err.println("File saved to run.xml"); } catch (TransformerException e) { System.err.println("CorpusReader: error when trying to print generated xml result file."); e.printStackTrace(); } }
From source file:org.ambraproject.article.service.XslIngestArchiveProcessor.java
/** * Run the zip file through the xsl stylesheet * * @param zip the zip archive containing the items to ingest * @param zipInfo the document describing the zip archive (adheres to zip.dtd) * @param articleXml the stylesheet to run on <var>zipInfo</var>; this is the main script * @param doiUrlPrefix DOI URL prefix/*from www . ja va 2 s . c om*/ * @return a document describing the fedora objects to create (must adhere to fedora.dtd) * @throws javax.xml.transform.TransformerException * if an error occurs during the processing */ private Document transformZip(ZipFile zip, String zipInfo, Document articleXml, String doiUrlPrefix) throws TransformerException, URISyntaxException { Transformer t = getTranslet(articleXml); t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); t.setURIResolver(new ZipURIResolver(zip)); // override the doi url prefix if one is specified in the config if (doiUrlPrefix != null) t.setParameter("doi-url-prefix", doiUrlPrefix); /* * Note: it would be preferable (and correct according to latest JAXP specs) to use * t.setErrorListener(), but Saxon does not forward <xls:message>'s to the error listener. * Hence we need to use Saxon's API's in order to get at those messages. */ final StringWriter msgs = new StringWriter(); MessageWarner em = new MessageWarner(); ((Controller) t).setMessageEmitter(em); t.setErrorListener(new ErrorListener() { public void warning(TransformerException te) { log.warn("Warning received while processing zip", te); } public void error(TransformerException te) { log.warn("Error received while processing zip", te); msgs.write(te.getMessageAndLocation() + '\n'); } public void fatalError(TransformerException te) { log.warn("Fatal error received while processing zip", te); msgs.write(te.getMessageAndLocation() + '\n'); } }); Source inp = new StreamSource(new StringReader(zipInfo), "zip:/"); DOMResult res = new DOMResult(); try { t.transform(inp, res); } catch (TransformerException te) { if (msgs.getBuffer().length() > 0) { log.error(msgs.getBuffer().toString()); throw new TransformerException(msgs.toString(), te); } else throw te; } if (msgs.getBuffer().length() > 0) throw new TransformerException(msgs.toString()); return (Document) res.getNode(); }
From source file:net.frontlinesms.plugins.forms.FormsPluginController.java
/** * Fabaris_a.zanchi This method inserts the designer software version number * in the outgoing xform It also creates an empty tag for the client version * * @param xmlContent the string representation of the xform *///from w ww. j a v a 2 s . co m public static String insertSoftwareVersionNumber(String xmlContent, Form form) throws Exception { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); InputSource inStream = new InputSource(); inStream.setCharacterStream(new StringReader(xmlContent)); org.w3c.dom.Document xmlDoc = docBuilder.parse(inStream); xmlDoc.getDocumentElement().normalize(); Node versionNode = xmlDoc.getElementsByTagName(DefaultComponentDescriptor.DESINGER_VERSION_TAGNAME + "_" + DefaultComponentDescriptor.DESIGNER_VERSION_INDEX).item(0); if (versionNode != null) { versionNode.setTextContent(form.getDesignerVersion()); } /* * NodeList nodeList = xmlDoc.getElementsByTagName("h:head"); Node * headNode = nodeList.item(0); Node modelNode = * xmlDoc.getElementsByTagName("model").item(0); Element newElemDesigner * = xmlDoc.createElement("designer_version"); Element newElemClient = * xmlDoc.createElement("client_version"); Node newNodeDesigner = (Node) * newElemDesigner; Node newNodeClient = (Node) newElemClient; String * designerVersion = form.getDesignerVersion(); if (designerVersion == * null) designerVersion = ""; * newNodeDesigner.appendChild(xmlDoc.createTextNode(designerVersion)); * newNodeClient.appendChild(xmlDoc.createTextNode("")); * headNode.insertBefore(newNodeDesigner, modelNode); * headNode.insertBefore(newNodeClient, modelNode); */ TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer trans = tFactory.newTransformer(); trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); StringWriter sWriter = new StringWriter(); Result result = new StreamResult(sWriter); trans.transform(new DOMSource(xmlDoc), result); String result2 = sWriter.getBuffer().toString(); System.out.println("-------- inserting version ------------"); System.out.println(result2); return result2; }
From source file:net.frontlinesms.plugins.forms.FormsPluginController.java
/** * Fabaris_a.zanchi Method to remove empty groups for outgoing messages so * that mobile tool doesn't crash/*w w w . j a v a 2s. c om*/ * * @param content an xml document (just xml without any additional content) * @return xml document without empty groups with attribute * appearance="field-list" * @throws Exception */ public static String removeEmptyGroups(String content) throws Exception { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); InputSource inStream = new InputSource(); inStream.setCharacterStream(new StringReader(content)); org.w3c.dom.Document xmlDoc = docBuilder.parse(inStream); xmlDoc.getDocumentElement().normalize(); NodeList groupList = xmlDoc.getElementsByTagName("group"); int i = 0; while (i < groupList.getLength()) { Element group = (Element) groupList.item(i); if (group.getAttribute("appearance").equals("field-list")) { if (group.getChildNodes().getLength() == 0) { groupList.item(i).getParentNode().removeChild(groupList.item(i)); i--; } if (group.getTextContent().equals(", ")) { groupList.item(i).getParentNode().removeChild(groupList.item(i)); i--; } } i++; } TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer trans = tFactory.newTransformer(); trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); StringWriter sWriter = new StringWriter(); Result result = new StreamResult(sWriter); trans.transform(new DOMSource(xmlDoc), result); String result2 = sWriter.getBuffer().toString(); System.out.println("---------- remove empty groups ---------"); System.out.println(result2); return result2; }