List of usage examples for org.w3c.dom Node getFirstChild
public Node getFirstChild();
From source file:edu.indiana.lib.twinpeaks.util.DomUtils.java
/** * Get any text associated with this element and it's children. Null if none. * @param parent the node containing text * @return Text//ww w . j av a 2s. co m */ public static String getAllText(Node parent) { String text = null; if (parent != null) { for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) { if (child.getNodeType() == Node.TEXT_NODE) { text = normalizeText(text, child.getNodeValue()); continue; } if (child.getNodeType() == Node.ELEMENT_NODE) { String childText = getText(child); if (childText != null) { text = normalizeText(text, childText); } } } } return text; }
From source file:com.nexmo.verify.sdk.NexmoVerifyClient.java
private static SearchResult parseSearchResult(Element root) throws IOException { String requestId = null;// ww w . j av a 2 s . co m String accountId = null; String number = null; String senderId = null; Date dateSubmitted = null; Date dateFinalized = null; Date firstEventDate = null; Date lastEventDate = null; float price = -1; String currency = null; SearchResult.VerificationStatus status = null; List<SearchResult.VerifyCheck> checks = new ArrayList<>(); String errorText = null; NodeList fields = root.getChildNodes(); for (int i = 0; i < fields.getLength(); i++) { Node node = fields.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) continue; String name = node.getNodeName(); if ("request_id".equals(name)) { requestId = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); } else if ("account_id".equals(name)) { accountId = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); } else if ("status".equals(name)) { String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); if (str != null) { try { status = SearchResult.VerificationStatus.valueOf(str.replace(' ', '_')); } catch (IllegalArgumentException e) { log.error("xml parser .. invalid value in <status> node [ " + str + " ] "); } } } else if ("number".equals(name)) { number = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); } else if ("price".equals(name)) { String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); try { if (str != null) price = Float.parseFloat(str); } catch (NumberFormatException e) { log.error("xml parser .. invalid value in <price> node [ " + str + " ] "); } } else if ("currency".equals(name)) { currency = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); } else if ("sender_id".equals(name)) { senderId = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); } else if ("date_submitted".equals(name)) { String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); if (str != null) { try { dateSubmitted = parseDateTime(str); } catch (ParseException e) { log.error("xml parser .. invalid value in <date_submitted> node [ " + str + " ] "); } } } else if ("date_finalized".equals(name)) { String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); if (str != null) { try { dateFinalized = parseDateTime(str); } catch (ParseException e) { log.error("xml parser .. invalid value in <date_finalized> node [ " + str + " ] "); } } } else if ("first_event_date".equals(name)) { String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); if (str != null) { try { firstEventDate = parseDateTime(str); } catch (ParseException e) { log.error("xml parser .. invalid value in <first_event_date> node [ " + str + " ] "); } } } else if ("last_event_date".equals(name)) { String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); if (str != null) { try { lastEventDate = parseDateTime(str); } catch (ParseException e) { log.error("xml parser .. invalid value in <last_event_date> node [ " + str + " ] "); } } } else if ("checks".equals(name)) { NodeList checkNodes = node.getChildNodes(); for (int j = 0; j < checkNodes.getLength(); j++) { Node checkNode = checkNodes.item(j); if (checkNode.getNodeType() != Node.ELEMENT_NODE) continue; if ("check".equals(checkNode.getNodeName())) checks.add(parseVerifyCheck((Element) checkNode)); } } else if ("error_text".equals(name)) { errorText = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue(); } } if (status == null) throw new IOException("Xml Parser - did not find a <status> node"); return new SearchResult(BaseResult.STATUS_OK, requestId, accountId, status, number, price, currency, senderId, dateSubmitted, dateFinalized, firstEventDate, lastEventDate, checks, errorText, false); }
From source file:Main.java
/** * Format generated xml doc by indentation * * @param node For java, rather than GWT * @param indent//from w ww.j a v a2 s . c om * @return */ public static String format(Node node, String indent) { StringBuilder formatted = new StringBuilder(); if (node.getNodeType() == Node.ELEMENT_NODE) { StringBuilder attributes = new StringBuilder(); for (int k = 0; k < node.getAttributes().getLength(); k++) { attributes.append(" "); attributes.append(node.getAttributes().item(k).getNodeName()); attributes.append("=\""); attributes.append(node.getAttributes().item(k).getNodeValue()); attributes.append("\""); } formatted.append(indent); formatted.append("<"); formatted.append(node.getNodeName()); formatted.append(attributes.toString()); if (!node.hasChildNodes()) { formatted.append("/>\n"); return formatted.toString(); } if ((node.hasChildNodes() && node.getFirstChild().getNodeType() == Node.TEXT_NODE)) { formatted.append(">"); } else { formatted.append(">\n"); } for (int i = 0; i < node.getChildNodes().getLength(); i++) { formatted.append(format(node.getChildNodes().item(i), indent + " ")); } if (node.hasChildNodes() && node.getFirstChild().getNodeType() != Node.TEXT_NODE) { formatted.append(indent); } formatted.append("</"); formatted.append(node.getNodeName()); formatted.append(">\n"); } else { String value = node.getTextContent().trim(); if (value.length() > 0) { formatted.append(value); } } return formatted.toString(); }
From source file:edu.indiana.lib.twinpeaks.util.DomUtils.java
/** * Get the text associated with this element at this level only, or * recursivley, searching through all child elements * @param parent the node containing text * @param recursiveSearch Search all child elements? * @return Text (trimmed of leading/trailing whitespace, null if none) *///from w w w.ja va 2 s . c o m public static String textSearch(Node parent, boolean recursiveSearch) { String text = null; if (parent != null) { for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) { switch (child.getNodeType()) { case Node.TEXT_NODE: text = normalizeText(text, child.getNodeValue()); break; case Node.ELEMENT_NODE: if (recursiveSearch) { text = normalizeText(text, getText(child)); } break; default: break; } } } return text == null ? text : text.trim(); }
From source file:net.java.sip.communicator.impl.history.HistoryReaderImpl.java
/** * If there is keyword restriction and doesn't match the conditions * return null. Otherwise return the HistoryRecord corresponding the * given nodes./*from ww w . j a v a2s. c om*/ * * @param propertyNodes NodeList * @param timestamp Date * @param keywords String[] * @param field String * @param caseSensitive boolean * @return HistoryRecord */ static HistoryRecord filterByKeyword(NodeList propertyNodes, Date timestamp, String[] keywords, String field, boolean caseSensitive) { ArrayList<String> nameVals = new ArrayList<String>(); int len = propertyNodes.getLength(); boolean targetNodeFound = false; for (int j = 0; j < len; j++) { Node propertyNode = propertyNodes.item(j); if (propertyNode.getNodeType() == Node.ELEMENT_NODE) { String nodeName = propertyNode.getNodeName(); Node nestedNode = propertyNode.getFirstChild(); if (nestedNode == null) continue; // Get nested TEXT node's value String nodeValue = nestedNode.getNodeValue(); // unescape xml chars, we have escaped when writing values nodeValue = StringEscapeUtils.unescapeXml(nodeValue); if (field != null && field.equals(nodeName)) { targetNodeFound = true; if (!matchKeyword(nodeValue, keywords, caseSensitive)) return null; // doesn't match the given keyword(s) // so return nothing } nameVals.add(nodeName); // Get nested TEXT node's value nameVals.add(nodeValue); } } // if we need to find a particular record but the target node is not // present skip this record if (keywords != null && keywords.length > 0 && !targetNodeFound) { return null; } String[] propertyNames = new String[nameVals.size() / 2]; String[] propertyValues = new String[propertyNames.length]; for (int j = 0; j < propertyNames.length; j++) { propertyNames[j] = nameVals.get(j * 2); propertyValues[j] = nameVals.get(j * 2 + 1); } return new HistoryRecord(propertyNames, propertyValues, timestamp); }
From source file:com.rapidminer.gui.OperatorDocLoader.java
/** * //w w w . j a v a2 s .c om * @param operatorWikiName * @param opDesc * @return The parsed <tt>Document</tt> (not finally parsed) of the selected operator. * @throws MalformedURLException * @throws ParserConfigurationException */ private static Document parseDocumentForOperator(String operatorWikiName, OperatorDescription opDesc) throws MalformedURLException, ParserConfigurationException { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setIgnoringComments(true); builderFactory.setIgnoringElementContentWhitespace(true); DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); documentBuilder.setEntityResolver(new XHTMLEntityResolver()); Document document = null; URL url = new URL(WIKI_PREFIX_FOR_OPERATORS + operatorWikiName); if (url != null) { try { document = documentBuilder.parse(WebServiceTools.openStreamFromURL(url)); } catch (IOException e) { logger.warning("Could not open " + url.toExternalForm() + ": " + e.getMessage()); } catch (SAXException e) { logger.warning("Could not parse operator documentation: " + e.getMessage()); } int i = 0; if (document != null) { Element contentElement = document.getElementById("content"); // removing content element from document if (contentElement != null) { contentElement.getParentNode().removeChild(contentElement); } // removing everything from body NodeList bodies = document.getElementsByTagName("body"); for (int k = 0; k < bodies.getLength(); k++) { Node body = bodies.item(k); while (body.hasChildNodes()) { body.removeChild(body.getFirstChild()); } // read content element to body if (contentElement != null && k == 0) { body.appendChild(contentElement); } } // removing everything from head NodeList heads = document.getElementsByTagName("head"); for (int k = 0; k < heads.getLength(); k++) { Node head = heads.item(k); while (head.hasChildNodes()) { head.removeChild(head.getFirstChild()); } } // removing...<head/> from document if (heads != null) { while (i < heads.getLength()) { Node head = heads.item(i); head.getParentNode().removeChild(head); } } // removing jump-to-nav element from document Element jumpToNavElement = document.getElementById("jump-to-nav"); if (jumpToNavElement != null) { jumpToNavElement.getParentNode().removeChild(jumpToNavElement); } // removing mw-normal-catlinks element from document Element mwNormalCatlinksElement = document.getElementById("mw-normal-catlinks"); if (mwNormalCatlinksElement != null) { mwNormalCatlinksElement.getParentNode().removeChild(mwNormalCatlinksElement); } // removing complete link navigation Element tocElement = document.getElementById("toc"); if (tocElement != null) { tocElement.getParentNode().removeChild(tocElement); } // removing everything from class printfooter NodeList nodeListDiv = document.getElementsByTagName("div"); for (int k = 0; k < nodeListDiv.getLength(); k++) { Element div = (Element) nodeListDiv.item(k); if (div.getAttribute("class").equals("printfooter")) { div.getParentNode().removeChild(div); } } // removing everything from class editsection NodeList spanList = document.getElementsByTagName("span"); for (int k = 0; k < spanList.getLength(); k++) { Element span = (Element) spanList.item(k); if (span.getAttribute("class").equals("editsection")) { span.getParentNode().removeChild(span); } } // Synopsis Header boolean doIt = true; NodeList pList = document.getElementsByTagName("p"); for (int k = 0; k < pList.getLength(); k++) { if (doIt) { Node p = pList.item(k); NodeList pChildList = p.getChildNodes(); for (int j = 0; j < pChildList.getLength(); j++) { Node pChild = pChildList.item(j); if (pChild.getNodeType() == Node.TEXT_NODE && pChild.getNodeValue() != null && StringUtils.isNotBlank(pChild.getNodeValue()) && StringUtils.isNotEmpty(pChild.getNodeValue())) { String pChildString = pChild.getNodeValue(); Element newPWithoutSpaces = document.createElement("p"); newPWithoutSpaces.setTextContent(pChildString); Node synopsis = document.createTextNode("Synopsis"); Element span = document.createElement("span"); span.setAttribute("class", "mw-headline"); span.setAttribute("id", "Synopsis"); span.appendChild(synopsis); Element h2 = document.createElement("h2"); h2.appendChild(span); Element div = document.createElement("div"); div.setAttribute("id", "synopsis"); div.appendChild(h2); div.appendChild(newPWithoutSpaces); Node pChildParentParent = pChild.getParentNode().getParentNode(); Node pChildParent = pChild.getParentNode(); pChildParentParent.replaceChild(div, pChildParent); doIt = false; break; } } } else { break; } } // removing all <br...>-Tags NodeList brList = document.getElementsByTagName("br"); while (i < brList.getLength()) { Node br = brList.item(i); Node parentBrNode = br.getParentNode(); parentBrNode.removeChild(br); } // removing everything from script NodeList scriptList = document.getElementsByTagName("script"); while (i < scriptList.getLength()) { Node scriptNode = scriptList.item(i); Node parentNode = scriptNode.getParentNode(); parentNode.removeChild(scriptNode); } // removing all empty <p...>-Tags NodeList pList2 = document.getElementsByTagName("p"); int ccc = 0; while (ccc < pList2.getLength()) { Node p = pList2.item(ccc); NodeList pChilds = p.getChildNodes(); int kk = 0; while (kk < pChilds.getLength()) { Node pChild = pChilds.item(kk); if (pChild.getNodeType() == Node.TEXT_NODE) { String pNodeValue = pChild.getNodeValue(); if (pNodeValue == null || StringUtils.isBlank(pNodeValue) || StringUtils.isEmpty(pNodeValue)) { kk++; } else { ccc++; break; } } else { ccc++; break; } if (kk == pChilds.getLength()) { Node parentBrNode = p.getParentNode(); parentBrNode.removeChild(p); } } } // removing firstHeading element from document Element firstHeadingElement = document.getElementById("firstHeading"); if (firstHeadingElement != null) { CURRENT_OPERATOR_NAME_READ_FROM_RAPIDWIKI = firstHeadingElement.getFirstChild().getNodeValue() .replaceFirst(".*:", ""); firstHeadingElement.getParentNode().removeChild(firstHeadingElement); } // setting operator plugin name if (opDesc != null && opDesc.getProvider() != null) { CURRENT_OPERATOR_PLUGIN_NAME = opDesc.getProvider().getName(); } // removing sitesub element from document Element siteSubElement = document.getElementById("siteSub"); if (siteSubElement != null) { siteSubElement.getParentNode().removeChild(siteSubElement); } // removing contentSub element from document Element contentSubElement = document.getElementById("contentSub"); if (contentSubElement != null) { contentSubElement.getParentNode().removeChild(contentSubElement); } // removing catlinks element from document Element catlinksElement = document.getElementById("catlinks"); if (catlinksElement != null) { catlinksElement.getParentNode().removeChild(catlinksElement); } // removing <a...> element from document, if they are empty NodeList aList = document.getElementsByTagName("a"); if (aList != null) { int k = 0; while (k < aList.getLength()) { Node a = aList.item(k); Element aElement = (Element) a; if (aElement.getAttribute("class").equals("internal")) { a.getParentNode().removeChild(a); } else { Node aChild = a.getFirstChild(); if (aChild != null && (aChild.getNodeValue() != null && aChild.getNodeType() == Node.TEXT_NODE && StringUtils.isNotBlank(aChild.getNodeValue()) && StringUtils.isNotEmpty(aChild.getNodeValue()) || aChild.getNodeName() != null)) { Element aChildElement = null; if (aChild.getNodeName().startsWith("img")) { aChildElement = (Element) aChild; Element imgElement = document.createElement("img"); imgElement.setAttribute("alt", aChildElement.getAttribute("alt")); imgElement.setAttribute("class", aChildElement.getAttribute("class")); imgElement.setAttribute("height", aChildElement.getAttribute("height")); imgElement.setAttribute("src", WIKI_PREFIX_FOR_IMAGES + aChildElement.getAttribute("src")); imgElement.setAttribute("width", aChildElement.getAttribute("width")); imgElement.setAttribute("border", "1"); Node aParent = a.getParentNode(); aParent.replaceChild(imgElement, a); } else { k++; } } else { a.getParentNode().removeChild(a); } } } } } } return document; }
From source file:DOMParsarDemo.java
public void printElement(Node node) { if (node.getNodeType() != Node.TEXT_NODE) { Node child = node.getFirstChild(); while (child != null) { if (node.getNodeName().equals("distance")) { if (child.getNodeName().equals("value")) { System.out.println(child.getFirstChild().getNodeValue()); }//w w w . j a v a 2 s . com } printElement(child); child = child.getNextSibling(); } } }
From source file:org.escidoc.browser.elabsmodul.service.ELabsService.java
private static InstrumentBean resolveInstrument(final ResourceProxy resourceProxy) throws EscidocBrowserException { if (resourceProxy == null || !(resourceProxy instanceof ItemProxy)) { throw new EscidocBrowserException("NOT an ItemProxy", null); }/*from www. j a va 2 s .c om*/ final ItemProxy itemProxy = (ItemProxy) resourceProxy; final InstrumentBean instrumentBean = new InstrumentBean(); instrumentBean.setObjectId(itemProxy.getId()); final Element e = itemProxy.getMetadataRecords().get("escidoc").getContent(); final NodeList nodeList = e.getChildNodes(); final String URI_DC = "http://purl.org/dc/elements/1.1/"; final String URI_EL = "http://escidoc.org/ontologies/bw-elabs/re#"; for (int i = 0; i < nodeList.getLength(); i++) { final Node node = nodeList.item(i); final String nodeName = node.getLocalName(); final String nsUri = node.getNamespaceURI(); if (nodeName == null || nodeName.equals("")) { continue; } else if (nsUri == null || nsUri.equals("")) { continue; } if ("title".equals(nodeName) && URI_DC.equals(nsUri)) { instrumentBean.setName((node.getFirstChild() != null) ? node.getFirstChild().getNodeValue() : null); } else if ("description".equals(nodeName) && URI_DC.equals(nsUri)) { instrumentBean.setDescription( (node.getFirstChild() != null) ? node.getFirstChild().getNodeValue() : null); } else if ("requires-configuration".equals(nodeName) && URI_EL.equals(nsUri)) { final String value = node.getFirstChild().getNodeValue(); if (value.equals("no")) { instrumentBean.setConfiguration(false); } else if (value.equals("yes")) { instrumentBean.setConfiguration(true); } } else if ("requires-calibration".equals(nodeName) && URI_EL.equals(nsUri)) { final String value = node.getFirstChild().getNodeValue(); if (value.equals("no")) { instrumentBean.setCalibration(false); } else if (value.equals("yes")) { instrumentBean.setCalibration(true); } } else if ("esync-endpoint".equals(nodeName) && URI_EL.equals(nsUri)) { instrumentBean.setESyncDaemon( (node.getFirstChild() != null) ? node.getFirstChild().getNodeValue() : null); } else if ("monitored-folder".equals(nodeName) && URI_EL.equals(nsUri)) { instrumentBean .setFolder((node.getFirstChild() != null) ? node.getFirstChild().getNodeValue() : null); } else if ("result-mime-type".equals(nodeName) && URI_EL.equals(nsUri)) { instrumentBean .setFileFormat((node.getFirstChild() != null) ? node.getFirstChild().getNodeValue() : null); } else if ("responsible-person".equals(nodeName) && URI_EL.equals(nsUri) && node.getAttributes().getNamedItem("rdf:resource") != null) { final String supervisorId = node.getAttributes().getNamedItem("rdf:resource").getNodeValue(); instrumentBean.setDeviceSupervisor(supervisorId); } else if ("institution".equals(nodeName) && URI_EL.equals(nsUri) && node.getAttributes().getNamedItem("rdf:resource") != null) { final String instituteId = node.getAttributes().getNamedItem("rdf:resource").getNodeValue(); instrumentBean.setInstitute(instituteId); } } return instrumentBean; }
From source file:Main.java
public static void spreadNamespaces(Node node, String tns, boolean overwrite) { Document doc = node instanceof Document ? (Document) node : node.getOwnerDocument(); boolean isParent = false; while (node != null) { Node next = null;//from w ww . j a v a2 s. c o m if (!isParent && node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNamespaceURI() == null) { node = doc.renameNode(node, tns, node.getNodeName()); } else { if (overwrite) { tns = node.getNamespaceURI(); } } NamedNodeMap nodeMap = node.getAttributes(); int nodeMapLengthl = nodeMap.getLength(); for (int i = 0; i < nodeMapLengthl; i++) { Node attr = nodeMap.item(i); if (attr.getNamespaceURI() == null) { doc.renameNode(attr, tns, attr.getNodeName()); } } } isParent = (isParent || (next = node.getFirstChild()) == null) && (next = node.getNextSibling()) == null; node = isParent ? node.getParentNode() : next; if (isParent && node != null) { if (overwrite) { tns = node.getNamespaceURI(); } } } }
From source file:be.ibridge.kettle.core.XMLHandler.java
/** * Get the value of a tag in a node/*from w ww . j av a 2 s. c o m*/ * @param n The node to look in * @param tag The tag to look for * @return The value of the tag or null if nothing was found. */ public static final String getTagValue(Node n, String tag) { NodeList children; Node childnode; if (n == null) return null; children = n.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { childnode = children.item(i); if (childnode.getNodeName().equalsIgnoreCase(tag)) { if (childnode.getFirstChild() != null) return childnode.getFirstChild().getNodeValue(); } } return null; }