List of usage examples for org.w3c.dom Document appendChild
public Node appendChild(Node newChild) throws DOMException;
newChild
to the end of the list of children of this node. From source file:com.sinet.gage.dlap.utils.XMLUtils.java
/** * @param String//ww w .ja v a 2 s .co m * @param String * @return String */ public static String parseXML(String xml, String rootElementName) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); DocumentBuilder db; db = dbf.newDocumentBuilder(); Document newDoc = db.parse(new ByteArrayInputStream(xml.getBytes())); Element element = (Element) newDoc.getElementsByTagName(rootElementName).item(0); // Imports a node from another document to this document, // without altering Document newDoc2 = db.newDocument(); // or removing the source node from the original document Node copiedNode = newDoc2.importNode(element, true); // Adds the node to the end of the list of children of this node newDoc2.appendChild(copiedNode); Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); Writer out = new StringWriter(); tf.transform(new DOMSource(newDoc2), new StreamResult(out)); return out.toString(); } catch (TransformerException | ParserConfigurationException | SAXException | IOException e) { LOGGER.error("Exception in parsing xml from response: ", e); } return ""; }
From source file:com.bluexml.side.Integration.alfresco.xforms.webscript.XmlBuilder.java
public static Document buildEntry(QName type, String objectId, Map<QName, Serializable> properties, List<AssociationBean> list) { // Document entry = new Document(); DocumentBuilder documentBuilder = null; try {//from www . ja v a 2s . com documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); throw new RuntimeException("Couldn't create a document builder."); } Document doc = documentBuilder.newDocument(); Element root = doc.createElement(ENTRY_ROOTNODE); root.setAttribute(ENTRY_QUALIFIEDNAME, type.getLocalName()); root.setAttribute(ENTRY_ID, objectId); Element attributesE = buildAttributes(doc, properties); Element associationsE = buildAssociations(doc, list); root.appendChild(attributesE); root.appendChild(associationsE); doc.appendChild(root); return doc; }
From source file:com.hangum.tadpole.engine.sql.util.QueryUtils.java
/** * query to xml//from w w w. jav a 2 s. c o m * * @param userDB * @param strQuery * @param listParam */ @SuppressWarnings("deprecation") public static String selectToXML(final UserDBDAO userDB, final String strQuery, final List<Object> listParam) throws Exception { final StringWriter stWriter = new StringWriter(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.newDocument(); final Element results = doc.createElement("Results"); doc.appendChild(results); SqlMapClient client = TadpoleSQLManager.getInstance(userDB); QueryRunner qr = new QueryRunner(client.getDataSource()); qr.query(strQuery, listParam.toArray(), new ResultSetHandler<Object>() { @Override public Object handle(ResultSet rs) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); while (rs.next()) { Element row = doc.createElement("Row"); results.appendChild(row); for (int i = 1; i <= metaData.getColumnCount(); i++) { String columnName = metaData.getColumnName(i); Object value = rs.getObject(i) == null ? "" : rs.getObject(i); Element node = doc.createElement(columnName); node.appendChild(doc.createTextNode(value.toString())); row.appendChild(node); } } return stWriter.toString(); } }); DOMSource domSource = new DOMSource(doc); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", 4); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//"ISO-8859-1"); StreamResult sr = new StreamResult(stWriter); transformer.transform(domSource, sr); return stWriter.toString(); }
From source file:com.hangum.tadpole.engine.sql.util.QueryUtils.java
/** * execute DML/*from w ww.j av a2 s . co m*/ * * @param userDB * @param strQuery * @param listParam * @param resultType * @throws Exception */ public static String executeDML(final UserDBDAO userDB, final String strQuery, final List<Object> listParam, final String resultType) throws Exception { SqlMapClient client = TadpoleSQLManager.getInstance(userDB); Object effectObject = runSQLOther(userDB, strQuery, listParam); String strReturn = ""; if (resultType.equals(RESULT_TYPE.CSV.name())) { final StringWriter stWriter = new StringWriter(); CSVWriter csvWriter = new CSVWriter(stWriter, ','); String[] arryString = new String[2]; arryString[0] = "effectrow"; arryString[1] = String.valueOf(effectObject); csvWriter.writeNext(arryString); strReturn = stWriter.toString(); } else if (resultType.equals(RESULT_TYPE.JSON.name())) { final JsonArray jsonArry = new JsonArray(); JsonObject jsonObj = new JsonObject(); jsonObj.addProperty("effectrow", String.valueOf(effectObject)); jsonArry.add(jsonObj); strReturn = JSONUtil.getPretty(jsonArry.toString()); } else {//if(resultType.equals(RESULT_TYPE.XML.name())) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.newDocument(); final Element results = doc.createElement("Results"); doc.appendChild(results); Element row = doc.createElement("Row"); results.appendChild(row); Element node = doc.createElement("effectrow"); node.appendChild(doc.createTextNode(String.valueOf(effectObject))); row.appendChild(node); DOMSource domSource = new DOMSource(doc); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", 4); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); final StringWriter stWriter = new StringWriter(); StreamResult sr = new StreamResult(stWriter); transformer.transform(domSource, sr); strReturn = stWriter.toString(); } return strReturn; }
From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.ooxml.AbstractOOXMLSignatureService.java
private static void addOriginSigsRels(final String signatureZipEntryName, final ZipOutputStream zipOutputStream) throws ParserConfigurationException, IOException, TransformerException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document originSignRelsDocument = documentBuilderFactory.newDocumentBuilder().newDocument(); final Element relationshipsElement = originSignRelsDocument.createElementNS(RELATIONSHIPS_SCHEMA, "Relationships"); //$NON-NLS-1$ relationshipsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", RELATIONSHIPS_SCHEMA); //$NON-NLS-1$ originSignRelsDocument.appendChild(relationshipsElement); final Element relationshipElement = originSignRelsDocument.createElementNS(RELATIONSHIPS_SCHEMA, "Relationship"); //$NON-NLS-1$ final String relationshipId = "rel-" + UUID.randomUUID().toString(); //$NON-NLS-1$ relationshipElement.setAttribute("Id", relationshipId); //$NON-NLS-1$ relationshipElement.setAttribute("Type", //$NON-NLS-1$ "http://schemas.openxmlformats.org/package/2006/relationships/digital-signature/signature"); //$NON-NLS-1$ relationshipElement.setAttribute("Target", FilenameUtils.getName(signatureZipEntryName)); //$NON-NLS-1$ relationshipsElement.appendChild(relationshipElement); zipOutputStream.putNextEntry(new ZipEntry("_xmlsignatures/_rels/origin.sigs.rels")); //$NON-NLS-1$ writeDocumentNoClosing(originSignRelsDocument, zipOutputStream, false); }
From source file:Main.java
public static Document makeEmptyXmlDocument(String rootElementName) { Document document = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true);// w w w. ja va 2s . c o m // factory.setNamespaceAware(true); try { DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.newDocument(); } catch (Exception e) { //Debug.logError(e, module); } if (document == null) return null; if (rootElementName != null) { Element rootElement = document.createElement(rootElementName); document.appendChild(rootElement); } return document; }
From source file:XMLUtils.java
/** * Creates a new document with a document root element. * @param name/*from w w w. ja va 2s .c om*/ * @return */ public static Element newElement(String name) { DocumentBuilder builder = null; try { builder = getParser(); Document doc = builder.newDocument(); Element el = doc.createElement(name); doc.appendChild(el); return el; } catch (ParserConfigurationException e) { throw new RuntimeException(e); } finally { releaseParser(builder); } }
From source file:sep.gaia.resources.poi.POILoaderWorker.java
/** * Generates a Overpass API-request in XML-format. The request complies to the limitations and the * bounding box in <code>query</code> and is designed to retrieve both nodes and recursed ways. * @param query The query to generate XML for. * @return The generated XML-query./*from w w w . ja v a 2s.com*/ */ private static String generateQueryXML(POIQuery query) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); // The root of a OSM-query is always osm-script: Element script = doc.createElement("osm-script"); doc.appendChild(script); // First element is the union containing the queries: Element unionElement = doc.createElement("union"); script.appendChild(unionElement); // Second element says that the recused union of the prior results should be formed: Element recurseUnion = doc.createElement("union"); Element itemElement = doc.createElement("item"); recurseUnion.appendChild(itemElement); Element recurseElement = doc.createElement("recurse"); recurseElement.setAttribute("type", "down"); recurseUnion.appendChild(recurseElement); script.appendChild(recurseUnion); // The last element means, that the results (of the recursed union) // should be written as response: Element printElement = doc.createElement("print"); script.appendChild(printElement); // First query (in the query union) askes for nodes conforming the given attributes: Element queryNodeElement = doc.createElement("query"); queryNodeElement.setAttribute("type", "node"); // The second element does the same for ways: Element queryWayElement = doc.createElement("query"); queryWayElement.setAttribute("type", "way"); // Add them to the first union: unionElement.appendChild(queryNodeElement); unionElement.appendChild(queryWayElement); // Now iterate all key-value-pairs and add "has-kv"-pairs to both queries: POIFilter filter = query.getLimitations(); Map<String, String> attributes = filter.getLimitations(); for (String key : attributes.keySet()) { String value = attributes.get(key); // The values returned by POIFilter are regular expressions, so use regv instead of v: Element currentKVNode = doc.createElement("has-kv"); currentKVNode.setAttribute("k", key); currentKVNode.setAttribute("regv", value); queryNodeElement.appendChild(currentKVNode); Element currentKVWay = doc.createElement("has-kv"); currentKVWay.setAttribute("k", key); currentKVWay.setAttribute("regv", value); queryWayElement.appendChild(currentKVWay); } // We don't want the data of the whole earth, so add bounding-boxes to the queries: Element nodeBBoxElement = createBBoxElement(doc, query.getBoundingBox()); queryNodeElement.appendChild(nodeBBoxElement); Element wayBBoxElement = createBBoxElement(doc, query.getBoundingBox()); queryWayElement.appendChild(wayBBoxElement); // Now the XML-tree is built, so transform it to a string and return it: TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); ByteArrayOutputStream stream = new ByteArrayOutputStream(); StreamResult result = new StreamResult(stream); transformer.transform(source, result); return stream.toString(); } catch (ParserConfigurationException | TransformerException e) { Logger.getInstance().error("Cannot write cache-index: " + e.getMessage()); return null; } }
From source file:com.photon.phresco.service.util.ServerUtil.java
/** * To create pom.xml file for artifact upload * //w ww. j a v a2 s.c om * @param info * @return * @throws PhrescoException */ public static File createPomFile(ArtifactGroup info) throws PhrescoException { FileWriter writer = null; File pomFile = getPomFile(); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder domBuilder = domFactory.newDocumentBuilder(); org.w3c.dom.Document newDoc = domBuilder.newDocument(); Element rootElement = newDoc.createElement(ServerConstants.POM_PROJECT); newDoc.appendChild(rootElement); Element modelVersion = newDoc.createElement(ServerConstants.POM_MODELVERSION); modelVersion.setTextContent(ServerConstants.POM_MODELVERSION_VAL); rootElement.appendChild(modelVersion); Element groupId = newDoc.createElement(ServerConstants.POM_GROUPID); groupId.setTextContent(info.getGroupId()); rootElement.appendChild(groupId); Element artifactId = newDoc.createElement(ServerConstants.POM_ARTIFACTID); artifactId.setTextContent(info.getArtifactId()); rootElement.appendChild(artifactId); Element version = newDoc.createElement(ServerConstants.POM_VERSION); version.setTextContent(info.getVersions().get(0).getVersion()); rootElement.appendChild(version); Element packaging = newDoc.createElement(ServerConstants.POM_PACKAGING); packaging.setTextContent(info.getPackaging()); rootElement.appendChild(packaging); Element description = newDoc.createElement(ServerConstants.POM_DESC); description.setTextContent(ServerConstants.POM_DESC_VAL); rootElement.appendChild(description); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ServerConstants.POM_OMMIT); trans.setOutputProperty(OutputKeys.INDENT, ServerConstants.POM_DESC); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(newDoc); trans.transform(source, result); String xmlString = sw.toString(); writer = new FileWriter(pomFile); writer.write(xmlString); writer.close(); } catch (Exception e) { throw new PhrescoException(e); } finally { Utility.closeStream(writer); } return pomFile; }
From source file:Main.java
public static void edit(Document doc) { Element root = doc.createElementNS(null, "person"); // Create Root Element Element item = doc.createElementNS(null, "name"); // Create element item.appendChild(doc.createTextNode("Jeff")); root.appendChild(item); // Attach element to Root element item = doc.createElementNS(null, "age"); // Create another Element item.appendChild(doc.createTextNode("28")); root.appendChild(item); // Attach Element to previous element down tree item = doc.createElementNS(null, "height"); item.appendChild(doc.createTextNode("1.80")); root.appendChild(item); // Attach another Element - grandaugther doc.appendChild(root); // Add Root to Document }