List of usage examples for org.w3c.dom Document createElement
public Element createElement(String tagName) throws DOMException;
From source file:Main.java
public static Node createNodeFromPath(Element modelElement, String path) { Document document = modelElement.getOwnerDocument(); StringTokenizer st = new StringTokenizer(path, "/"); while (st.hasMoreTokens()) { String t = st.nextToken(); if (st.hasMoreTokens()) { if (t.equals("..")) { modelElement = (Element) modelElement.getParentNode(); } else { Element elm = getFirstChildElement(modelElement, t); if (elm == null) modelElement = (Element) modelElement.insertBefore(document.createElement(t), getFirstChildElement(modelElement, t)); else modelElement = elm;/*from www . j a va 2 s . c o m*/ } } else { modelElement = (Element) modelElement.insertBefore(document.createElement(t), getFirstChildElement(modelElement, t)); } } return modelElement; }
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 .j a v a2s. c o m*/ */ 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:XMLUtils.java
/** * Creates a new document with a document root element. * @param name//from w ww. jav a 2 s .c o m * @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:Main.java
public static void nodeSubUpdate(Element root, String table, String queryType, String queryValue) { Node find = getTag(root, table); Document doc = find.getOwnerDocument(); NodeList nl = find.getChildNodes(); int numnodes = nl.getLength(); System.out.println("length : " + numnodes); Node replNode = null;//from w w w . j a v a 2 s .c o m for (int i = 0; i < numnodes; i++) { Node n = nl.item(i); String name = n.getNodeName(); if (name.equals(queryType)) { replNode = n; System.out.println("Finding Node : " + replNode.getNodeName()); break; } } Element type = doc.createElement(queryType); Text value = doc.createTextNode(queryValue); type.appendChild(value); find.replaceChild(type, replNode); print(doc); }
From source file:eu.europeana.uim.sugarcrmclient.internal.helpers.ClientUtils.java
/** * Creates a SelectFields Soap Object given a List<String> fieldnames object * which sets the fields to be retrieved. * /* w ww .j av a 2s . c om*/ * @param fieldnames * @return */ public static SelectFields generatePopulatedSelectFields(List<String> fieldnames) { SelectFields selfields = new SelectFields(); StringBuffer arrayType = new StringBuffer(); arrayType.append("string["); arrayType.append(fieldnames.size()); arrayType.append("]"); CommonAttributes commonAttributes = new CommonAttributes(); commonAttributes.setHref(arrayType.toString()); selfields.setCommonAttributes(commonAttributes); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); for (String fieldname : fieldnames) { Element element = document.createElement("string"); Array array = new Array(); array.getAnyList(); selfields.setArray(array); element.appendChild(document.createTextNode(fieldname)); } } catch (ParserConfigurationException e) { e.printStackTrace(); return null; } return selfields; }
From source file:com.viettel.ws.client.JDBCUtil.java
/** * Create document using DOM api//w w w.ja v a 2 s . c om * * @param rs a result set * @param doc a input document for append content * @param rsName name of the appended element * @return a document after append content * @throws ParserConfigurationException If error when parse XML string * @throws SQLException If error when read data from database */ public static Document add2Document1(ResultSet rs1, ResultSet rs2, Document doc, String rsName) throws ParserConfigurationException, SQLException { if (rs1 == null && rs2 == null) { return doc; } //Get root element Element root = doc.getDocumentElement(); Element rsElement = doc.createElement(rsName); root.appendChild(rsElement); if (rs1 != null) { ResultSetMetaData rsmd = rs1.getMetaData(); int colCount = rsmd.getColumnCount(); while (rs1.next()) { Element row = doc.createElement("Row"); rsElement.appendChild(row); try { for (int i = 1; i <= colCount; i++) { String columnName = rsmd.getColumnName(i); Object value = rs1.getObject(i); if (value == null) { value = ""; } Element node = doc.createElement(columnName); node.appendChild(doc.createTextNode(value.toString())); row.appendChild(node); } } catch (Exception ex) { LogUtil.addLog(ex);//binhnt sonar a160901 // logger.error(e, e); } } } if (rs2 != null) { ResultSetMetaData rsmd = rs2.getMetaData(); int colCount = rsmd.getColumnCount(); while (rs2.next()) { Element row = doc.createElement("Row"); rsElement.appendChild(row); try { for (int i = 1; i <= colCount; i++) { String columnName = rsmd.getColumnName(i); Object value = rs2.getObject(i); if (value == null) { value = ""; } Element node = doc.createElement(columnName); node.appendChild(doc.createTextNode(value.toString())); row.appendChild(node); } } catch (Exception ex) { LogUtil.addLog(ex);//binhnt sonar a160901 // logger.error(e, e); } } } return doc; }
From source file:com.msopentech.odatajclient.engine.data.ODataBinder.java
private static Element toNullPropertyElement(final ODataProperty prop, final Document doc) { final Element element = doc.createElement(ODataConstants.PREFIX_DATASERVICES + prop.getName()); element.setAttribute(ODataConstants.ATTR_NULL, Boolean.toString(true)); return element; }
From source file:com.twinsoft.convertigo.engine.util.CarUtils.java
private static Document exportProject(Project project, final List<TestCase> selectedTestCases) throws EngineException { try {//from ww w . j ava 2s .c om final Document document = XMLUtils.getDefaultDocumentBuilder().newDocument(); // ProcessingInstruction pi = document.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\""); // document.appendChild(pi); final Element rootElement = document.createElement("convertigo"); rootElement.setAttribute("version", com.twinsoft.convertigo.engine.Version.fullProductVersion); rootElement.setAttribute("engine", com.twinsoft.convertigo.engine.Version.version); rootElement.setAttribute("beans", com.twinsoft.convertigo.beans.Version.version); String studioVersion = ""; try { Class<?> c = Class.forName("com.twinsoft.convertigo.eclipse.Version"); studioVersion = (String) c.getDeclaredField("version").get(null); } catch (Exception e) { } catch (Throwable th) { } rootElement.setAttribute("studio", studioVersion); document.appendChild(rootElement); new WalkHelper() { protected Element parentElement = rootElement; @Override protected void walk(DatabaseObject databaseObject) throws Exception { Element parentElement = this.parentElement; Element element = parentElement; element = databaseObject.toXml(document); String name = " : " + databaseObject.getName(); try { name = CachedIntrospector.getBeanInfo(databaseObject.getClass()).getBeanDescriptor() .getDisplayName() + name; } catch (IntrospectionException e) { name = databaseObject.getClass().getSimpleName() + name; } Integer depth = (Integer) document.getUserData("depth"); if (depth == null) { depth = 0; } String openpad = StringUtils.repeat(" ", depth); String closepad = StringUtils.repeat(" ", depth); parentElement.appendChild(document.createTextNode("\n")); parentElement.appendChild( document.createComment(StringUtils.rightPad(openpad + "<" + name + ">", 150))); if (databaseObject instanceof TestCase && selectedTestCases.size() > 0) { if (selectedTestCases.contains((TestCase) databaseObject)) { parentElement.appendChild(element); } } else { parentElement.appendChild(element); } document.setUserData("depth", depth + 1, null); this.parentElement = element; super.walk(databaseObject); element.appendChild(document.createTextNode("\n")); element.appendChild( document.createComment(StringUtils.rightPad(closepad + "</" + name + ">", 150))); document.setUserData("depth", depth, null); databaseObject.hasChanged = false; databaseObject.bNew = false; this.parentElement = parentElement; } }.init(project); return document; } catch (Exception e) { throw new EngineException("Unable to export the project \"" + project.getName() + "\".", e); } }
From source file:it.intecs.pisa.toolbox.util.URLReader.java
public static Document getDirectoryStructure(String url) throws Exception { Document urlTree = new DOMUtil().newDocument(); Element rootNode = urlTree.createElement("urlContent"); urlTree.appendChild(rootNode);/* w w w. ja v a 2s . c o m*/ try { getContent(url, urlTree, rootNode); } catch (Exception e) { e.printStackTrace(System.out); return null; } return urlTree; }
From source file:eu.europeana.uim.sugarcrmclient.internal.helpers.ClientUtils.java
/** * Creates a NameValueList Soap Element given a List<String> namevalues * object which sets the fields to be retrieved. * //from w w w . j ava 2s . c o m * @param fieldnames * @return */ public static NameValueList generatePopulatedNameValueList(List<NameValue> namevalues) { NameValueList namevalueList = new NameValueList(); StringBuffer arrayType = new StringBuffer(); arrayType.append("name_value["); arrayType.append(namevalues.size()); arrayType.append("]"); Array array = new Array(); ArrayType arrTypeObj = new ArrayType(); arrTypeObj.setArrayType(arrayType.toString()); ArrayAttributes atts = new ArrayAttributes(); atts.setArrayType(arrTypeObj); namevalueList.setArrayAttributes(atts); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); for (NameValue namevalue : namevalues) { Element name_value = document.createElement("name_value"); Element name = document.createElement("name"); Element value = document.createElement("value"); name.appendChild(document.createTextNode(namevalue.getName())); value.appendChild(document.createTextNode(namevalue.getValue())); name_value.appendChild(name); name_value.appendChild(value); array.getAnyList().add(name_value); } namevalueList.setArray(array); } catch (ParserConfigurationException e) { e.printStackTrace(); return null; } return namevalueList; }