/** * @param source * @param result * @param outputKeys */ static void transform(Source source, Result result, Map<String, String> outputKeys) { Assertion.assertNotNull("source", source); Assertion.assertNotNull("result", result); try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); if (outputKeys != null && !outputKeys.isEmpty()) { for (String name : outputKeys.keySet()) { String value = outputKeys.get(name); if (!TextUtil.isBlank(value)) { transformer.setOutputProperty(name, value); } } } transformer.transform(source, result); } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } }
public static void main(String[] args) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element root = document.createElement("Languages"); root.setAttribute("cat", "it"); Element lan1 = document.createElement("lan"); lan1.setAttribute("id", "1"); Element name1 = document.createElement("name"); name1.setTextContent("Java"); Element ide1 = document.createElement("ide"); ide1.setTextContent("Eclipse"); lan1.appendChild(name1); lan1.appendChild(ide1); Element lan2 = document.createElement("lan"); lan1.setAttribute("id", "2"); Element name2 = document.createElement("name"); name1.setTextContent("Swift"); Element ide2 = document.createElement("ide"); ide1.setTextContent("Xcode"); lan1.appendChild(name2); lan1.appendChild(ide2); Element lan3 = document.createElement("lan"); lan1.setAttribute("id", "1"); Element name3 = document.createElement("name"); name1.setTextContent("Java"); Element ide3 = document.createElement("ide"); ide1.setTextContent("Eclipse"); lan1.appendChild(name3); lan1.appendChild(ide3); root.appendChild(lan1); root.appendChild(lan2); root.appendChild(lan3); document.appendChild(root); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(writer)); System.out.println(writer.toString()); transformer.transform(new DOMSource(document), new StreamResult("newXML.xml")); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
protected void processDocument(Document document, PrintWriter writer) { String type = new StencilSetUtil().getStencilSet(document); SyntaxChecker checker = null; if (type != null) { if (type.equals("bpmn.json") || type.equals("bpmneec.json")) checker = getCheckerBPMN(document); else if (type.equals("bpmn1.1.json")) checker = getCheckerBPMN11(document); else if (type.equals("ibpmn.json")) checker = getCheckerIBPMN(document); else if (type.equals("interactionpetrinets.json")) checker = getCheckerIPN(document); else if (type.equals("epc.json")) checker = getCheckerEPC(document); } if (checker == null) { // try eRDF try { NamedNodeMap map = XPathAPI.selectSingleNode(document, "//a[@rel='oryx-stencilset']").getAttributes(); type = map.getNamedItem("href").getNodeValue(); } catch (TransformerException e) { e.printStackTrace(); } if (type != null && type.endsWith("petrinet.json")) { checker = getCheckerPetriNet(document); } } if (checker == null) { writer.print("{}"); } else { checker.checkSyntax(); writer.print(checker.getErrorsAsJson().toString()); } }
/** Creates a batch file */ private void createCpBatFile() { try { StreamSource xsltSource = new StreamSource(new File("src/main/resources/xslt/cpbat.xslt")); StreamSource xmlSource = new StreamSource(new File("project.xml")); Transformer t = TransformerFactory.newInstance().newTransformer(xsltSource); StreamResult cpBatResult = new StreamResult(new File("src/main/config/metaz/autogeneratedcp.bat")); t.transform(xmlSource, cpBatResult); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } }
private void runXsltScript() { JFileChooser fc = new JFileChooser(); fc.setDialogTitle("Select XSLT script"); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); int returnVal = fc.showOpenDialog(null); if (returnVal == 1) { return; } File fXSLT = fc.getSelectedFile(); File fXML = new File("C:/Odin/Repository/"); boolean isDirectory = fXML.isDirectory(); /* Code adapted from: http://blog.msbbc.co.uk/2007/06/simple-saxon-java-example.html * [Accessed 3rd-Sept-2010] */ for (File format : fXML.listFiles()) { boolean isSuccessful = false; try { System.setProperty( "javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl"); TransformerFactory tFact = TransformerFactory.newInstance(); Transformer tf = tFact.newTransformer(new StreamSource(fXSLT)); tf.transform(new StreamSource(format), new StreamResult(format)); isSuccessful = true; } catch (TransformerException tX) { tX.printStackTrace(); } finally { System.out.println( "Change of file " + format.getName() + " was successful? " + isSuccessful); } } }
private void writeXmlDocument(File file, Document doc) { try { // set up a transformer TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); // create string from xml tree FileWriter writer = new FileWriter(file); StreamResult result = new StreamResult(writer); DOMSource source = new DOMSource(doc); trans.transform(source, result); writer.close(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * Print the the trace of methods from where the error originated. This will trace all nested * exception objects, as well as this object. * * @param s The stream where the dump will be sent to. */ public void printStackTrace(java.io.PrintStream s) { if (s == null) s = System.err; try { super.printStackTrace(s); } catch (Exception e) { } Throwable exception = m_exception; for (int i = 0; (i < 10) && (null != exception); i++) { s.println("---------"); exception.printStackTrace(s); if (exception instanceof TransformerException) { TransformerException se = (TransformerException) exception; Throwable prev = exception; exception = se.getException(); if (prev == exception) break; } else { exception = null; } } }
public static void createXMLFile(Document doc, File file) { try { 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); String xmlString = result.getWriter().toString(); // write to file // Create file if it does not exist boolean success = file.createNewFile(); if (success) { // File did not exist and was created boolean append = false; FileWriter fw = new FileWriter(file, append); fw.write(xmlString); fw.close(); } else { // File already exists boolean append = false; FileWriter fw = new FileWriter(file, append); fw.write(xmlString); // appends the string to the file fw.close(); } } catch (TransformerException e) { e.printStackTrace(); } catch (IOException io) { io.printStackTrace(); } }
/** * Command line expression tester used to try out filters and expressions. * * @param args */ public static final void main(String[] args) { System.out.println("ECQL Filters Tester"); System.out.println("Seperate with \";\" or \"quit\" to finish)"); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); FilterTransformer filterTransformer = new FilterTransformer(); filterTransformer.setIndentation(4); while (true) { System.out.print(">"); String line = null; try { line = reader.readLine(); if (line.equals("quit")) { System.out.println("Bye!"); break; } List<Filter> filters = ECQL.toFilterList(line); for (Filter filter : filters) { System.out.println(); filterTransformer.transform(filter, System.out); } } catch (IOException e1) { e1.printStackTrace(); } catch (CQLException cqlex) { System.out.println(cqlex.getSyntaxError()); } catch (TransformerException e) { e.printStackTrace(); } } }
/** * Pomocnicza klasa wysyłająca dokument XML do writera * * @param doc dokument, który chcemy wysłać * @param out Writer, do którego chcemy pisać */ private void XML2Writer(Document doc, PrintWriter out) { Transformer transformer = null; try { transformer = TransformerFactory.newInstance().newTransformer(); } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } StreamResult result = new StreamResult(out); DOMSource source = new DOMSource(doc); try { if (transformer != null) { transformer.transform(source, result); } } catch (TransformerException e) { e.printStackTrace(); } }
public void parseStatusXml(String statusXml) { try { Document statusDoc = SubmissionUtils.emptyDocument(); SubmissionUtils.transform(new StringReader(statusXml), statusDoc); if (statusDoc.getDocumentElement().getTagName().equals("error")) { String runName = statusDoc.getElementsByTagName("RunName").item(0).getTextContent(); String runDirRegex = "(\\d{6})_([A-z0-9]+)_(\\d+)_[A-z0-9_]*"; Matcher m = Pattern.compile(runDirRegex).matcher(runName); if (m.matches()) { setStartDate(new SimpleDateFormat("yyMMdd").parse(m.group(1))); setInstrumentName(m.group(2)); } setRunName(runName); setHealth(HealthType.Unknown); } else { String runStarted = statusDoc.getElementsByTagName("RunStarted").item(0).getTextContent(); setStartDate(new SimpleDateFormat("EEEE, MMMMM dd, yyyy h:mm aaa").parse(runStarted)); setInstrumentName( statusDoc.getElementsByTagName("InstrumentName").item(0).getTextContent()); setRunName(statusDoc.getElementsByTagName("RunName").item(0).getTextContent()); setHealth(HealthType.Unknown); } setXml(statusXml); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } }
private void soapMessage(String path, String wsName, String wsPortName) { try { URL wsdlURL = new URL(APP_SERVER + path); final String NS = AbstractServiceImpl.WS_TARGET_NAMESPACE; Service service = Service.create(wsdlURL, new QName(NS, wsName)); Dispatch<Source> dispatcher = service.createDispatch(new QName(NS, wsPortName), Source.class, Service.Mode.PAYLOAD); Source request = new StreamSource(new StringReader("<hello/>")); Source response = dispatcher.invoke(request); assertNotNull(response); Transformer transformer = TransformerFactory.newInstance().newTransformer(); final StringWriter writer = new StringWriter(); Result output = new StreamResult(writer); transformer.transform(response, output); Message message = new Message("clientMessages"); message.dumpFormattedMessage( EchoServiceClient.class, Message.LevelEnum.INFO, "receivedAnswer", writer.toString()); } catch (MalformedURLException e) { e.printStackTrace(); fail(String.valueOf(e)); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } }
@SuppressWarnings("unchecked") public static ArrayList<String> getNameSpaces(String baseURL) { ArrayList<String> res = new ArrayList<String>(); OAIPMHtype xmlType = null; ListMetadataFormats list = null; try { list = new ListMetadataFormats(baseURL); String xmlRec = list.toString(); if (xmlRec.startsWith("<?")) { int offset = xmlRec.indexOf("?>"); xmlRec = xmlRec.substring(offset + 2); } InputStream is = new ByteArrayInputStream(xmlRec.getBytes("UTF-8")); JAXBElement<OAIPMHtype> oai = (JAXBElement<OAIPMHtype>) u.unmarshal(is); xmlType = oai.getValue(); ArrayList<MetadataFormatType> res0 = (ArrayList<MetadataFormatType>) xmlType.getListMetadataFormats().getMetadataFormat(); Iterator<MetadataFormatType> itr = res0.iterator(); while (itr.hasNext()) { MetadataFormatType typ = itr.next(); res.add(typ.getMetadataPrefix()); } } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (JAXBException e) { e.printStackTrace(); } return res; }
public static String getStringFromDocument(Document doc) { try { doc.normalize(); DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); // transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); int indent = 2; if (indent > 0) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent)); } // transformer.transform(domSource, result); return writer.toString(); } catch (TransformerException ex) { ex.printStackTrace(); return null; } }
/** * convert an xml document to a string * * @param node document node * @return a string representation of the xml document */ public static String xmlToString(Node node, String encoding) { String retXmlAsString = ""; try { Source source = new DOMSource(node); StringWriter stringWriter = new StringWriter(); Result result = new StreamResult(stringWriter); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, encoding); transformer.transform(source, result); retXmlAsString = stringWriter.toString(); // for some reason encoding is not handling entity references - need // to look in to the further retXmlAsString = retXmlAsString.replace(" ", " "); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } return retXmlAsString; }
private String combineData() { String content = ""; XMLBuilder builder = null; int index = 0; String[] tags; boolean isEntry = contentArray.size() != 2; if (isEntry) { tags = new String[] { "date-created", "time-created", "latitude", "longitude", "first-name", "middle-name", "last-name", "birthday", "age", "gender", "address", "slide-number", "region", "case", "species", "drugs-given", "exam-result", "remarks" }; } else { tags = new String[] {"user", "pass"}; } try { if (isEntry) builder = XMLBuilder.create("entry"); else builder = XMLBuilder.create("credentials"); Log.d("MakeTextFile", String.valueOf(contentArray.size())); for (String data : contentArray) { builder.element(tags[index++]).text(data); Log.v("WRITE", "CONTENT: " + data); } Properties outputProperties = new Properties(); outputProperties.put(javax.xml.transform.OutputKeys.METHOD, "xml"); outputProperties.put(javax.xml.transform.OutputKeys.INDENT, "yes"); outputProperties.put("{http://xml.apache.org/xslt}indent-amount", "2"); outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes"); content = builder.asString(outputProperties); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } return content; }
public void saveCurrentRoute(View view) { if (GPS_captureStarted) { Log.w("Saving Route", "Can't Save, tracking not paused"); return; } Element metadata = gpx_document.createElement("metadata"); Element filename = gpx_document.createElement("name"); Element author = gpx_document.createElement("author"); Element trackName = gpx_document.createElement("name"); String fn = "TestFile"; String tn = "TestTrack"; String auth = "Username"; filename.appendChild(gpx_document.createTextNode(fn)); author.appendChild(gpx_document.createTextNode(auth)); trackName.appendChild(gpx_document.createTextNode(tn)); track.appendChild(trackName); metadata.appendChild(filename); metadata.appendChild(author); rootElement.appendChild(metadata); try { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnected(); Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMSource source = new DOMSource(gpx_document); StreamResult result; if (isConnected) { result = new StreamResult(new StringWriter()); transformer.transform(source, result); String gpx = result.getWriter().toString(); Request.send_GPX(gpx); } else { FileOutputStream stream = openFileOutput(fn + ".gpx", MODE_PRIVATE); result = new StreamResult(stream); transformer.transform(source, result); Log.i("writing file", "success"); filesToSync.put(fn + ".gpx", true); } } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public void ExportMongoCollection( String mongoCollectionName, String xmlCollectionName, String xmlOutputFileName, HashSet fields) throws Exception { BasicDBList mongoCollection = GetDBList(mongoCollectionName, null); try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement(xmlCollectionName); doc.appendChild(rootElement); for (int i = 0; i < mongoCollection.size(); i++) { Element thisElement = doc.createElement( mongoCollectionName); // the xml nodes are named after the mongoColleciton BasicDBObject record = (BasicDBObject) mongoCollection.get(i); Object attributeArray[] = fields.toArray(); for (int j = 0; j < fields.size(); j++) { String attribName = (String) attributeArray[j]; String attribValue = record.getString(attribName); // Attr thisAttr = doc.createAttribute(attribName); // thisAttr.setValue(attribValue); thisElement.setAttribute(attribName, attribValue); } rootElement.appendChild(thisElement); } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); String filePath = System.getProperty("user.home") + "/" + xmlOutputFileName; File f = new File(filePath); // StreamResult result = new StreamResult(new File("/" + xmlOutputFileName)); StreamResult result = new StreamResult(f.toURI().getPath()); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } }
public static void main(String[] args) { // TODO Auto-generated method stub try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // Создание корневого элемента Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("company"); doc.appendChild(rootElement); // дочерние элементы Element staff = doc.createElement("Staff"); rootElement.appendChild(staff); // добавление аттрибутов Attr attr = doc.createAttribute("id"); attr.setValue("1"); staff.setAttributeNode(attr); // другой способ // staff.setAttribute("id", "1"); Element firstname = doc.createElement("firstname"); firstname.appendChild(doc.createTextNode("yong")); staff.appendChild(firstname); Element lastname = doc.createElement("lastname"); lastname.appendChild(doc.createTextNode("mook kim")); staff.appendChild(lastname); Element nickname = doc.createElement("nickname"); nickname.appendChild(doc.createTextNode("mkyong")); staff.appendChild(nickname); Element salary = doc.createElement("salary"); salary.appendChild(doc.createTextNode("100000")); staff.appendChild(salary); // Запись контента в xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("Export.xml")); transformer.transform(source, result); System.out.println("File saved!"); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } ModifyXMLFile mxf = new ModifyXMLFile(); mxf.ModifyFile(); }
public void write(Document doc, String fileName, Boolean swing) { try { File f = new File("."); String appPath = f.getAbsolutePath().substring(0, f.getAbsolutePath().length() - 1); File fout = new File( appPath.substring(0, appPath.length() - 16) + "SwingApp" + File.separator + "model" + File.separator + fileName + ".xml"); if (!swing) { // F:\workspace\github\KROKI-mockup-tool\ApplicationRepository\generated\model fout = new File( appPath.substring(0, appPath.length() - 16) + "ApplicationRepository" + File.separator + "generated" + File.separator + File.separator + "model" + File.separator + fileName + ".xml"); } if (!fout.getParentFile().exists()) if (!fout.getParentFile().mkdirs()) { throw new IOException("Greska pri kreiranju izlaznog direktorijuma "); } System.out.println("XML Writer writing " + fout.getAbsolutePath()); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(fout); transformer.transform(source, result); System.out.println("[XML WRITER] " + fileName + ".xml datoteka generisana"); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } }
public static void main(String argv[]) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("company"); doc.appendChild(rootElement); // 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("yong")); staff.appendChild(firstname); // lastname elements Element lastname = doc.createElement("lastname"); lastname.appendChild(doc.createTextNode("mook kim")); staff.appendChild(lastname); // nickname elements Element nickname = doc.createElement("nickname"); nickname.appendChild(doc.createTextNode("mkyong")); 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(".\\file.xml")); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } }
/* * (non-Javadoc) * @see addressbook.model.PersistenceAccess#save() */ public void save() throws IOException { // Create new DOM document Document document = null; try { document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Put content to document final Element ab = document.createElement("AddressBook"); document.appendChild(ab); for (Entry e : entries) { // Create new Entry element in address book element final Element entry = document.createElement("Entry"); ab.appendChild(entry); // Add name and gender entry.setAttribute("FirstName", e.getFirstName()); entry.setAttribute("SurName", e.getSurName()); entry.setAttribute("Gender", e.isMale() ? "M" : "F"); entry.setAttribute("DateOfBirth", Entry.dateFormatter.print(e.getDateOfBirth())); // Add contact information final Element contact = document.createElement("Contact"); if (e.getContactInformation() instanceof PhoneNumber) { contact.setAttribute("type", "phone"); } else if (e.getContactInformation() instanceof EmailAddress) { contact.setAttribute("type", "email"); } contact.setTextContent(e.getContactInformation().toString()); entry.appendChild(contact); } // Write document to file final FileOutputStream out = new FileOutputStream(dataFile); try { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "2"); // Platform specific... transformer.transform(new DOMSource(document), new StreamResult(out)); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } out.close(); }
@Override public Object retrieveWikiPage(String wikiLabel, String pageLabel) { String path = WIKIS_PATH + wikiLabel + PAGE_PATH + pageLabel + PAGE_ENTRY_AND_OPTIONS_PATH; System.out.printf("Connecting to %s at %s \n", path, this.uri.toString()); WebTarget webTarget = client .target(uri) .path("wikis") .path("basic") .path("api") .path("wiki") .path(wikiLabel) .path("page") .path(pageLabel) .path("entry") .queryParam("acls", "true") .queryParam("includeTags", "true"); System.out.printf("Invoking %s\n", webTarget.getUri().toString()); Response response = webTarget.request(MediaType.APPLICATION_ATOM_XML).get(); System.out.println("Reading response..."); // try (InputStream in = response.readEntity(InputStream.class)) { // SyndFeed feed = new SyndFeedInput().build(new XmlReader(in)); // new SyndFeedOutput().output(feed, new PrintWriter(System.out)); // return feed; // } catch (IOException | FeedException ex) { // ex.printStackTrace(); // throw new RuntimeException(ex); // } // String s = response.readEntity(String.class); Document document = response.readEntity(Document.class); document.getDocumentElement().normalize(); NodeList nodeList = document.getElementsByTagName("content"); if (nodeList.getLength() == 1) { Node node = nodeList.item(0); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; String src = element.getAttribute("src"); System.out.printf(">>>>> Content SRC: %s\n", src); } } try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMSource source = new DOMSource(document); File file = new File(pageLabel.replaceAll("\\s+", "") + ".xml"); StreamResult result = new StreamResult(file); transformer.transform(source, result); System.out.printf("File saved! %s\n", file.getAbsolutePath()); } catch (TransformerException ex) { ex.printStackTrace(); } // System.out.println("***** JERSEY plain String Feed..."); // System.out.println(s); // System.out.println("***** JERSEY plain String Feed..."); return document; }
private void button_Write_save() { Spinner spinner; Text text; // ディレクトリの作成 String target_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Yukari/Write/Pregnancy"; File dir = new File(target_path); if (!dir.exists()) { dir.mkdirs(); } DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder dbuilder = dbfactory.newDocumentBuilder(); Document document = dbuilder.newDocument(); Element root = document.createElement("members"); // edittextの中身を保存 for (int i1 = 0; i1 < item_checkup_EditText_8.length; i1++) { Element element1 = document.createElement(item_checkup_EditText_8tag[i1]); String string1 = ((EditText) findViewById(item_checkup_EditText_8[i1])).getText().toString(); text = document.createTextNode(string1); element1.appendChild(text); root.appendChild(element1); } document.appendChild(root); TransformerFactory tffactory = TransformerFactory.newInstance(); Transformer transformer = tffactory.newTransformer(); // 保存ファイルの作成 String filePath = Environment.getExternalStorageDirectory() + filepath; File file = new File(filePath); file.getParentFile().mkdir(); transformer.transform(new DOMSource(document), new StreamResult(file)); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } Toast.makeText(this, "保存が完了しました", Toast.LENGTH_LONG).show(); Intent intent_cancel = new Intent(getApplicationContext(), pregnancy_inspection_record.class); startActivity(intent_cancel); finish(); }
private void transform(StreamSource xmlStream, StreamSource xslStream, StreamResult result) { try { TransformerFactory factory = TransformerFactory.newInstance(); Templates template = factory.newTemplates(xslStream); Transformer transformer = template.newTransformer(); transformer.transform(xmlStream, result); } catch (TransformerException e) { e.printStackTrace(); } }
public void writeData(int personNumber, int stepId) { try { String filepath = "DataByPerson-" + personNumber + ".xml"; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(filepath); // Get the root element Node Data = doc.getFirstChild(); Element step = doc.createElement("Step"); Data.appendChild(step); Attr attr = doc.createAttribute("Number"); attr.setValue("" + stepId + ""); step.setAttributeNode(attr); // xPos elements Element xPosition = doc.createElement("X-Position"); xPosition.appendChild(doc.createTextNode("" + xPos + "")); step.appendChild(xPosition); // yPos elements Element yPosition = doc.createElement("Y-Position"); yPosition.appendChild(doc.createTextNode("" + yPos + "")); step.appendChild(yPosition); // Delta X elements Element deltaX = doc.createElement("Horizontal_Movement"); deltaX.appendChild(doc.createTextNode("" + movedDistanceX + "")); step.appendChild(deltaX); // Delta Y elements Element deltaY = doc.createElement("Vertical_Movement"); deltaY.appendChild(doc.createTextNode("" + movedDistanceY + "")); step.appendChild(deltaY); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(filepath)); transformer.transform(source, result); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (SAXException sae) { sae.printStackTrace(); } }
private void createTestModel0(final I_EXP_Format exportFormat) throws Exception { final File directory = getTestModelDirectory(); final File file = new File(directory, getTestModelFileName(exportFormat)); final ExportHelper expHelper = new ExportHelper(getCtx(), getAD_Client_ID()); final IReplicationAccessContext racCtx = new ReplicationAccessContext(10, false); // TODO hardcoded final Document doc = expHelper.exportRecord( (MEXPFormat) LegacyAdapters.convertToPO(exportFormat), "", MReplicationStrategy.REPLICATION_TABLE, X_AD_ReplicationTable.REPLICATIONTYPE_Merge, ModelValidator.TYPE_AFTER_CHANGE, racCtx); if (doc == null) { addLog( "Not creating test XML for format '" + exportFormat.getName() + "', because with AD_Client_ID=" + getAD_Client_ID() + "the system can't access any '" + exportFormat.getAD_Table().getName() + "'-record"); return; } // Save the document to the disk file final TransformerFactory tranFactory = TransformerFactory.newInstance(); final Transformer aTransformer = tranFactory.newTransformer(); aTransformer.setOutputProperty(OutputKeys.METHOD, "xml"); aTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); final Source src = new DOMSource(doc); // =================================== Write to String final Writer writer = new StringWriter(); final Result dest2 = new StreamResult(writer); aTransformer.transform(src, dest2); // =================================== Write to Disk try { final Result dest = new StreamResult(file); aTransformer.transform(src, dest); writer.flush(); writer.close(); } catch (TransformerException ex) { ex.printStackTrace(); throw ex; } addLog("Created test model: " + file); }
/** @param args */ public static void main(String[] args) { CustomerController cc = new CustomerController(); List<DaoObject> customerList = cc.listObjects(); List<String> customerNumbers = new ArrayList<String>(); SearchCardController scc = new SearchCardController(); try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element root = doc.createElement("Root"); doc.appendChild(root); CustomersAndCardToXMLExporter exporter = new CustomersAndCardToXMLExporter(); if (customerList != null && customerList.size() > 0) { System.out.println(customerList.size() + " Kunden gefunden"); if (customerList.size() > 1) { Iterator it = customerList.iterator(); while (it.hasNext()) { Customer cus = (Customer) it.next(); String cNumber = cus.getCustomernumber(); List<CardBean> cards = scc.performSearch(new Integer(cus.getId())); doc = exporter.export(doc, root, cus, cards); } } } else { System.out.println("Kein Customer gefunden"); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); String dfs = "yyyy-MM-dd_HH-mm-ss"; StreamResult result = new StreamResult(new File("C:\\temp\\Export-" + DateUtils.now(dfs) + ".xml")); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } // sc.readData(customerNumbers); }
public void getPlayerSummaries(ArrayList<Player> players) { String playerIDs = String.format("%d", players.get(0).getAccID64()); for (int i = 1; i < players.size(); i++) { playerIDs = String.format("%s,%d", playerIDs, players.get(i).getAccID64()); } String address = String.format( "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=%s&format=xml&steamids=%s", Core.APIKEY, playerIDs); System.out.println(address); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { URL url = new URL(address); URLConnection conn = url.openConnection(); DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.parse(conn.getInputStream()); TransformerFactory factory = TransformerFactory.newInstance(); Transformer xform = factory.newTransformer(); xform.transform(new DOMSource(doc), new StreamResult(System.out)); NodeList nl = doc.getElementsByTagName("player"); org.w3c.dom.Element e; for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) { e = (org.w3c.dom.Element) nl.item(i); players.get(i).setName(e.getElementsByTagName("personaname").item(0).getTextContent()); } } } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * Return a XML with config * * @param path Path for saving de config * @param config GUIConfig */ public static void saveXMLFromGUIConfig(String path, GUIConfig config) { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder; Document doc = null; try { docBuilder = docFactory.newDocumentBuilder(); // root elements doc = docBuilder.newDocument(); Element rootElement = doc.createElement("gui-configuration"); doc.appendChild(rootElement); Element language = doc.createElement("language"); language.setTextContent(config.getLanguage()); rootElement.appendChild(language); Element recentConfigFiles = doc.createElement("recentConfigFiles"); rootElement.appendChild(recentConfigFiles); for (String configFilePath : config.getRecentConfigFiles()) { Element configFile = doc.createElement("configFile"); configFile.setTextContent(configFilePath); recentConfigFiles.appendChild(configFile); } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); // At the moment we are not to validate Scheme // validateSchema(doc, Constants.configSchemaFilePath); // normalize text representation doc.getDocumentElement().normalize(); StreamResult result = new StreamResult(new File(path)); transformer.transform(source, result); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } }