List of usage examples for org.w3c.dom Document createTextNode
public Text createTextNode(String data);
Text
node given the specified string. From source file:Main.java
/** * * Convenience method to transfer a node (and all of its children) from one * * DOM XML document to another.//w ww .ja v a 2 s. co m * * * * Note: this method is recursive. * * * * @param current the current Element to append the transfer to * * @param target the target document for the transfer * * @param n the Node to transfer * * @return Element the current element. */ public static Element transferNode(Element current, Document target, Node n) { String name = n.getNodeName(); String value = n.getNodeValue(); short type = n.getNodeType(); if (type == Node.ELEMENT_NODE) { // create a new element for this node in the target document Element e = target.createElement(name); // move all the attributes over to the target document NamedNodeMap attrs = n.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node a = attrs.item(i); e.setAttribute(a.getNodeName(), a.getNodeValue()); } // get the children for this node NodeList children = n.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { // transfer each of the children to the new document transferNode(e, target, children.item(i)); } // append the node to the target document element current.appendChild(e); } else if (type == Node.TEXT_NODE) { Text text = target.createTextNode(value); current.appendChild(text); } return current; }
From source file:Main.java
public static void vectorToXML222(String xmlFile, String xpath, String parentNodeName, Vector<HashMap> vector) { File file = new File(xmlFile); try {/* w w w .j ava 2 s .c om*/ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document; Element rootNode; if (file.exists()) { document = documentBuilder.parse(new File(xmlFile)); rootNode = document.getDocumentElement(); } else { document = documentBuilder.newDocument(); rootNode = document.createElement(xpath); document.appendChild(rootNode); } for (int x = 0; x < vector.size(); x++) { Element parentNode = document.createElement(parentNodeName); rootNode.appendChild(parentNode); HashMap hashmap = vector.get(x); Set set = hashmap.entrySet(); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry me = (Map.Entry) i.next(); // System.out.println("key=" + // me.getKey().toString()); Element em = document.createElement(me.getKey().toString()); em.appendChild(document.createTextNode(me.getValue().toString())); parentNode.appendChild(em); // System.out.println("write " + // me.getKey().toString() + // "=" // + me.getValue().toString()); } } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(document); FileOutputStream fo = new FileOutputStream(xmlFile); StreamResult result = new StreamResult(fo); transformer.transform(source, result); } catch (Exception ex) { file.delete(); ex.printStackTrace(); } }
From source file:com.granule.json.utils.XML.java
private static void convertJSONArray(Document doc, Element parent, JSONArray jArray, String tagName) { tagName = removeProblemCharacters(tagName); for (int i = 0; i < jArray.size(); i++) { Element element = doc.createElement(tagName); if (parent != null) { parent.appendChild(element); } else {/*from w ww .j a v a 2s .c o m*/ doc.appendChild(element); } Object obj = jArray.get(i); if (obj instanceof Number) { Node tNode = doc.createTextNode(obj.toString()); element.appendChild(tNode); } else if (obj instanceof Boolean) { Node tNode = doc.createTextNode(obj.toString()); element.appendChild(tNode); } else if (obj instanceof String) { Node tNode = doc.createTextNode(escapeEntityCharacters(obj.toString())); element.appendChild(tNode); } else if (obj instanceof JSONObject) { convertJSONObject(doc, element, (JSONObject) obj, "jsonObject"); } else if (obj instanceof JSONArray) { convertJSONArray(doc, element, (JSONArray) obj, "jsonArray"); } } }
From source file:com.zimbra.cs.service.AutoDiscoverServlet.java
private static String createResponseDoc(String displayName, String email, String serviceUrl) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);/*from www . j a v a 2 s.co m*/ DocumentBuilder builder = factory.newDocumentBuilder(); Document xmlDoc = builder.newDocument(); Element root = xmlDoc.createElementNS(NS, "Autodiscover"); root.setAttribute("xmlns", NS); root.setAttribute("xmlns:xsi", XSI_NS); root.setAttribute("xmlns:xsd", XSD_NS); xmlDoc.appendChild(root); //Add the response element. Element response = xmlDoc.createElementNS(NS_MOBILE, "Response"); root.appendChild(response); //Add culture to to response Element culture = xmlDoc.createElement("Culture"); culture.appendChild(xmlDoc.createTextNode("en:en")); response.appendChild(culture); //User Element user = xmlDoc.createElement("User"); Element displayNameElm = xmlDoc.createElement("DisplayName"); displayNameElm.appendChild(xmlDoc.createTextNode(displayName)); user.appendChild(displayNameElm); Element emailAddr = xmlDoc.createElement("EMailAddress"); emailAddr.appendChild(xmlDoc.createTextNode(email)); user.appendChild(emailAddr); response.appendChild(user); //Action Element action = xmlDoc.createElement("Action"); Element settings = xmlDoc.createElement("Settings"); Element server = xmlDoc.createElement("Server"); Element type = xmlDoc.createElement("Type"); type.appendChild(xmlDoc.createTextNode("MobileSync")); server.appendChild(type); Element url = xmlDoc.createElement("Url"); url.appendChild(xmlDoc.createTextNode(serviceUrl)); server.appendChild(url); Element name = xmlDoc.createElement("Name"); name.appendChild(xmlDoc.createTextNode(serviceUrl)); server.appendChild(name); settings.appendChild(server); action.appendChild(settings); response.appendChild(action); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(xmlDoc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.transform(source, result); writer.flush(); String xml = writer.toString(); writer.close(); //manually generate xmlns for Autodiscover and Response element, this works //for testexchangeconnectivity.com, but iOS and Android don't like Response's xmlns // StringBuilder str = new StringBuilder(); // str.append("<?xml version=\"1.0\"?>\n"); // str.append("<Autodiscover xmlns:xsd=\"").append(XSD_NS).append("\""); // str.append(" xmlns:xsi=\"").append(XSI_NS).append("\""); // str.append(" xmlns=\"").append(NS).append("\">\n"); // int respIndex = xml.indexOf("<Response>"); // str.append("<Response xmlns=\"").append(NS_MOBILE).append("\">"); // str.append(xml.substring(respIndex + "<Response>".length(), xml.length())); // return str.toString(); return "<?xml version=\"1.0\"?>\n" + xml; }
From source file:eu.europa.esig.dss.DSSXMLUtils.java
/** * This method creates and adds a new XML {@code Element} with text value * * @param document root document// w w w . j ava 2 s . c om * @param parentDom parent node * @param namespace namespace * @param name element name * @param value element text node value * @return added element */ public static Element addTextElement(final Document document, final Element parentDom, final String namespace, final String name, final String value) { final Element dom = document.createElementNS(namespace, name); parentDom.appendChild(dom); final Text valueNode = document.createTextNode(value); dom.appendChild(valueNode); return dom; }
From source file:Main.java
/** * Converts a map to XML, where parent is the parent element, and every * other element is of the form <key>value</key> or <listElementName>listvalue</listElementName> * for each list index. The list elements MUST be Strings if they are to * have text nodes. But, they may also be another Map with key/value * pairs./* ww w . j a va 2 s.co m*/ * <p/> * We assume that every key is an actual XML compatible element name; i.e. a * String object. The values will be XML encoded automatically. * * @param elements the elements, whether a list of elements or a map * of key/value pairs * @param parentElement the parent element to append the new child to * @param document the XML document to create new elements in * @param listElementName the name for the element, for every element in the * List * * @throws ParserConfigurationException if a configuration error occurs */ public static void mapToNode(final Object elements, final Element parentElement, final Document document, final String listElementName) throws ParserConfigurationException { Object value; if (elements instanceof Map) { final Map map = (Map) elements; final Iterator it = map.keySet().iterator(); Element tmp; while (it.hasNext()) { final String key = (String) it.next(); value = map.get(key); if (value instanceof Map) { tmp = document.createElement(key); mapToNode(value, tmp, document, null); parentElement.appendChild(tmp); } else if (value instanceof List) { mapToNode(value, parentElement, document, key); } else { tmp = document.createElement(key); if (value != null) { // null elements don't get in tmp.appendChild(document.createTextNode((String) value)); parentElement.appendChild(tmp); } } } } else if (elements instanceof List) { if (listElementName == null || "".equals(listElementName.trim())) { throw new IllegalArgumentException( "listElementName can never be null if a list is passed " + "in for elements"); } final List list = (List) elements; for (int index = 0; index < list.size(); index++) { final Object element = list.get(index); if (element instanceof String) { // text node final String text = (String) list.get(index); final Element tmp = document.createElement(listElementName); tmp.appendChild(document.createTextNode(text)); parentElement.appendChild(tmp); } else if (element instanceof Map) { // sub elements that have key/value pairs, or key/List pairs final Element tmp = document.createElement(listElementName); parentElement.appendChild(tmp); mapToNode(element, tmp, document, null); } else if (element instanceof List) { throw new IllegalArgumentException( "List not supported " + "inside of List, cannot determine element name"); } } } else { throw new IllegalArgumentException("unsupported class type for " + "mapToXML"); } }
From source file:de.betterform.xml.xforms.model.constraints.RelevanceSelector.java
private static void addChildren(Element relevantElement, Node instanceNode) { Document ownerDocument = relevantElement.getOwnerDocument(); NodeList instanceChildren = instanceNode.getChildNodes(); for (int index = 0; index < instanceChildren.getLength(); index++) { Node instanceChild = (Node) instanceChildren.item(index); if (isEnabled(instanceChild)) { switch (instanceChild.getNodeType()) { case Node.TEXT_NODE: /* rather not, otherwise we cannot follow specs when * serializing to multipart/form-data for example *// w w w . j ava 2 s .com // denormalize text for better whitespace handling during serialization List list = DOMWhitespace.denormalizeText(instanceChild.getNodeValue()); for (int item = 0; item < list.size(); item++) { relevantElement.appendChild(ownerDocument.createTextNode(list.get(item).toString())); } */ relevantElement.appendChild(ownerDocument.createTextNode(instanceChild.getNodeValue())); break; case Node.CDATA_SECTION_NODE: relevantElement.appendChild(ownerDocument.createCDATASection(instanceChild.getNodeValue())); break; case Node.ELEMENT_NODE: addElement(relevantElement, instanceChild); break; default: // ignore break; } } } }
From source file:com.zimbra.cs.service.AutoDiscoverServlet.java
private static String createResponseDocForEws(String displayName, String email, String serviceUrl, Account acct) throws Exception { Provisioning prov = Provisioning.getInstance(); Server server = prov.getServer(acct); String cn = server.getCn();//from w w w . j a v a 2 s.co m String name = server.getName(); String acctId = acct.getId(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document xmlDoc = builder.newDocument(); Element root = xmlDoc.createElementNS(NS, "Autodiscover"); root.setAttribute("xmlns", NS); root.setAttribute("xmlns:xsi", XSI_NS); root.setAttribute("xmlns:xsd", XSD_NS); xmlDoc.appendChild(root); //Add the response element. Element response = xmlDoc.createElementNS(NS_OUTLOOK, "Response"); root.appendChild(response); //User Element user = xmlDoc.createElement("User"); Element displayNameElm = xmlDoc.createElement("DisplayName"); displayNameElm.appendChild(xmlDoc.createTextNode(displayName)); user.appendChild(displayNameElm); Element emailAddr = xmlDoc.createElement("EmailAddress"); emailAddr.appendChild(xmlDoc.createTextNode(email)); user.appendChild(emailAddr); Element depId = xmlDoc.createElement("DeploymentId"); depId.appendChild(xmlDoc.createTextNode(acctId)); user.appendChild(depId); response.appendChild(user); //Action Element account = xmlDoc.createElement("Account"); Element acctType = xmlDoc.createElement("AccountType"); acctType.appendChild(xmlDoc.createTextNode("email")); account.appendChild(acctType); response.appendChild(account); Element action = xmlDoc.createElement("Action"); action.appendChild(xmlDoc.createTextNode("settings")); account.appendChild(action); Element protocol = xmlDoc.createElement("Protocol"); account.appendChild(protocol); Element type = xmlDoc.createElement("Type"); type.appendChild(xmlDoc.createTextNode("EXCH")); protocol.appendChild(type); Element ews = xmlDoc.createElement("EwsUrl"); protocol.appendChild(ews); ews.appendChild(xmlDoc.createTextNode(serviceUrl)); Element as = xmlDoc.createElement("ASUrl"); protocol.appendChild(as); as.appendChild(xmlDoc.createTextNode(serviceUrl)); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(xmlDoc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.transform(source, result); writer.flush(); String xml = writer.toString(); writer.close(); return "<?xml version=\"1.0\"?>\n" + xml; }
From source file:org.openmrs.module.atomfeed.AtomFeedUtil.java
/** * Converts the given object to an xml entry * //from w w w. j a va2s. co m * @param action what is happenening * @param object the object being changed * @return atom feed xml entry string * @should return valid entry xml data */ protected static String getEntry(String action, OpenmrsObject object) { try { // We need a Document DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); // ////////////////////// // Creating the XML tree // create the root element and add it to the document Element root = doc.createElement("entry"); doc.appendChild(root); // the title element is REQUIRED // create title element, add object class, and add to root Element title = doc.createElement("title"); Text titleText = doc.createTextNode(action + ":" + object.getClass().getName()); title.appendChild(titleText); root.appendChild(title); // create link to view object details Element link = doc.createElement("link"); link.setAttribute("href", AtomFeedUtil.getViewUrl(object)); root.appendChild(link); // the id element is REQUIRED // create id element Element id = doc.createElement("id"); Text idText = doc.createTextNode("urn:uuid:" + object.getUuid()); id.appendChild(idText); root.appendChild(id); // the updated element is REQUIRED // create updated element, set current date Element updated = doc.createElement("updated"); // TODO: try to discover dateChanged/dateCreated from object -- ATOM-2 // instead? Text updatedText = doc.createTextNode(dateToRFC3339(getUpdatedValue(object))); updated.appendChild(updatedText); root.appendChild(updated); // the author element is REQUIRED // add author element, find creator Element author = doc.createElement("author"); Element name = doc.createElement("name"); Text nameText = doc.createTextNode(getAuthor(object)); name.appendChild(nameText); author.appendChild(name); root.appendChild(author); // the summary element is REQUIRED // add a summary Element summary = doc.createElement("summary"); Text summaryText = doc.createTextNode(object.getClass().getSimpleName() + " -- " + action); summary.appendChild(summaryText); root.appendChild(summary); Element classname = doc.createElement("classname"); Text classnameText = doc.createTextNode(object.getClass().getName()); classname.appendChild(classnameText); root.appendChild(classname); Element actionElement = doc.createElement("action"); Text actionText = doc.createTextNode(action); actionElement.appendChild(actionText); root.appendChild(actionElement); /* * Print the xml to the string */ // set up a transformer TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "no"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); trans.transform(source, result); return sw.toString(); } catch (Exception e) { log.error("unable to create entry string for: " + object); return ""; } }
From source file:com.meltmedia.cadmium.core.util.WarUtils.java
/** * Adds vHost and context-root mappings to a jboss-web.xml file contained withing a zip/war file. * @param inZip The zip file that the original jboss-web.xml file is in. * @param outZip The zip output stream to write the updated jboss-web.xml file to. * @param jbossWeb The zip element that represents the jboss-web.xml file. * @param domain The domain to add a vHost for. * @param context The context to add a context-root for. * @throws Exception/* w w w . java2 s.co m*/ */ public static void updateDomain(ZipFile inZip, ZipOutputStream outZip, ZipEntry jbossWeb, String domain, String context) throws Exception { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(inZip.getInputStream(jbossWeb)); Element rootNode = null; NodeList nodes = doc.getElementsByTagName("jboss-web"); if (nodes.getLength() == 1) { rootNode = (Element) nodes.item(0); } if (domain != null && domain.length() > 0) { Element vHost = doc.createElement("virtual-host"); removeNodesByTagName(rootNode, "virtual-host"); vHost.appendChild(doc.createTextNode(domain)); rootNode.appendChild(vHost); } if (context != null && context.length() > 0) { Element cRoot = doc.createElement("context-root"); removeNodesByTagName(rootNode, "context-root"); cRoot.appendChild(doc.createTextNode(context)); rootNode.appendChild(cRoot); } storeXmlDocument(outZip, jbossWeb, doc); }