List of usage examples for org.w3c.dom Node hasChildNodes
public boolean hasChildNodes();
From source file:Main.java
/** Goes through and adds newlines and indent to the current node and all its children * @param current the current node/* w w w .j a va2s . c o m*/ * @param indent the current level of indent this is increased recursively*/ private static void addFormatting(Document doc, Node current, String indent) { // go through each of the children adding space as required Node child = current.getFirstChild(); String childIndent = indent + "\t"; while (child != null) { Node nextChild = child.getNextSibling(); if (child.getNodeType() != Node.TEXT_NODE) { // Only if we aren't a text node do we add the space current.insertBefore(doc.createTextNode("\n" + childIndent), child); if (child.hasChildNodes()) { addFormatting(doc, child, childIndent); } if (nextChild == null) { // Because this is the last child, we need to add some space after it current.appendChild(doc.createTextNode("\n" + indent)); } } child = nextChild; } }
From source file:XMLReader.java
/** Returns element value * @param elem element (it is XML tag)//ww w . j a v a 2 s. c om * @return Element value otherwise empty String */ private final static String getElementValue(Node elem) { Node kid; if (elem != null) { if (elem.hasChildNodes()) { for (kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling()) { if (kid.getNodeType() == Node.TEXT_NODE) { return kid.getNodeValue(); } } } } return ""; }
From source file:Main.java
private static Node actualFindNodeWithAttributeValue(Node node, String name, String attribute, String value) { String nodeName = node.getNodeName(); nodeName = nodeName.substring((nodeName.indexOf(":") != -1 ? nodeName.indexOf(":") + 1 : 0)); if (nodeName.equals(name)) { Element e = (Element) node; if (e.getAttribute(attribute) != null && e.getAttribute(attribute).equals(value)) return node; }//from w ww . j a v a 2 s. co m if (node.hasChildNodes()) { NodeList list = node.getChildNodes(); int size = list.getLength(); for (int i = 0; i < size; i++) { Node found = actualFindNodeWithAttributeValue(list.item(i), name, attribute, value); if (found != null) return found; } } return null; }
From source file:Main.java
public static String retrieveNodeAsString(Node node) { String nodeStr = new String("<"); nodeStr += node.getNodeName() + internal; if (node.hasAttributes()) { NamedNodeMap attrs = node.getAttributes(); // add the attrubite name-value pairs for (int i = 0; i < attrs.getLength(); i++) { Node a = attrs.item(i); nodeStr += a.getNodeName() + "=" + a.getNodeValue() + internal; }//w w w. ja v a2s. c o m } if (node.hasChildNodes()) { nodeStr += ">\n"; NodeList ns = node.getChildNodes(); for (int i = 0; i < ns.getLength(); i++) { nodeStr += logXMLSubNode(ns.item(i), 1); } nodeStr += "<" + node.getNodeName() + "/>\n"; } else { nodeStr += "/>\n"; } return nodeStr; }
From source file:com.hp.test.framework.generatejellytess.GenerateJellyTests.java
public static void getData(Node parentNode, Node node) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: { if (node.toString().contains("Verification")) { System.out.println("******" + node.toString()); verfiy = true;/* www.ja va 2 s . co m*/ } if (node.hasChildNodes()) { NodeList list = node.getChildNodes(); int size = list.getLength(); for (int index = 0; index < size; index++) { getData(node, list.item(index)); } } break; } case Node.TEXT_NODE: { String data = node.getNodeValue(); if (data.trim().length() > 0) { Locators.put(parentNode.getNodeName(), node.getNodeValue()); } break; } } }
From source file:Models.Geographic.Repository.RepositoryGoogle.java
/** * Method that geocoding a address from google api * @param country/*from w ww . j av a 2 s. c om*/ * @param adm1 * @param adm2 * @param adm3 * @param local_area * @param locality * @param uncertainty * @return */ public static Location georenferencing(String country, String adm1, String adm2, String adm3, String local_area, String locality, double uncertainty) { Location a = null; String key; try { key = FixData.generateKey(new String[] { country, adm1, adm2, adm3, local_area, locality }); if (RepositoryGoogle.db == null) RepositoryGoogle.db = new HashMap(); if (RepositoryGoogle.db.containsKey(key)) return (Location) RepositoryGoogle.db.get(key); String data = (!locality.equals("") ? locality : "") + (!local_area.equals("") ? local_area + "+,+" : "") + (!adm3.equals("") ? adm3 + "+,+" : "") + (!adm2.equals("") ? adm2 + "+,+" : "") + (!adm1.equals("") ? adm1 + "+,+" : "") + (!country.equals("") ? country + "+,+" : ""); URL url = new URL(Configuration.getParameter("geocoding_google_url_send_xml") + "address=" + data.replace(" ", "%20").replace(".", "").replace(";", "")); URL file_url = new URL( url.getProtocol() + "://" + url.getHost() + signRequest(url.getPath(), url.getQuery())); // Get information from URL DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // Create a proxy to work in CIAT (erase this in another place) //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy2.ciat.cgiar.org", 8080)); DocumentBuilder db = dbf.newDocumentBuilder(); //Document doc = db.parse(file_url.openConnection(proxy).getInputStream()); Document doc = db.parse(file_url.openConnection().getInputStream()); // Document with data if (doc != null) { NodeList locationList = doc.getElementsByTagName("location"); NodeList locationTypeList = doc.getElementsByTagName("location_type"); NodeList viewPortList = doc.getElementsByTagName("viewport"); Node location = null, lat = null, lng = null; if (locationList.getLength() > 0) { for (int i = 0; i < locationList.getLength(); i++) { location = locationList.item(i); if (location.hasChildNodes()) { lat = location.getChildNodes().item(1); lng = location.getChildNodes().item(3); } } Node locationType = null; if (locationTypeList.getLength() > 0) { for (int i = 0; i < locationTypeList.getLength(); i++) locationType = locationTypeList.item(i); } Node viewPort = null, northeast = null, southwest = null, lat_northeast = null, lng_northeast = null, lat_southwest = null, lng_southwest = null; if (viewPortList.getLength() > 0) { for (int i = 0; i < viewPortList.getLength(); i++) { viewPort = viewPortList.item(i); if (viewPort.hasChildNodes()) { northeast = viewPort.getChildNodes().item(1); southwest = viewPort.getChildNodes().item(3); } /* Extract data from viewport field */ if (northeast.hasChildNodes()) { lat_northeast = northeast.getChildNodes().item(1); lng_northeast = northeast.getChildNodes().item(3); } if (southwest.hasChildNodes()) { lat_southwest = southwest.getChildNodes().item(1); lng_southwest = southwest.getChildNodes().item(3); } } } double[] coordValues = new double[] { Double.parseDouble(lat.getTextContent()), Double.parseDouble(lng.getTextContent()) }; double[] coordValuesNortheast = new double[] { Double.parseDouble(lat_northeast.getTextContent()), Double.parseDouble(lng_northeast.getTextContent()) }; double[] coordValuesSouthwest = new double[] { Double.parseDouble(lat_southwest.getTextContent()), Double.parseDouble(lng_southwest.getTextContent()) }; double distance = FixData.getDistance(coordValuesNortheast, coordValuesSouthwest); // Distance - km between Northeast and Southeast if (distance <= uncertainty) a = new Location(coordValues[0], coordValues[1], distance); else { RepositoryGoogle.db.put(key, a); throw new Exception("Exceede uncertainty. " + "Uncertainty: " + distance + " THRESHOLD: " + Configuration.getParameter("geocoding_threshold")); } } } RepositoryGoogle.db.put(key, a); } catch (NoSuchAlgorithmException | InvalidKeyException | URISyntaxException | IOException | ParserConfigurationException | SAXException ex) { System.out.println(ex); } catch (Exception ex) { System.out.println(ex); } return a; }
From source file:de.itomig.itoplib.GetItopData.java
private static String getConcatNodeValues(Node prop) { // behaves well for non-existing nodes and for node values which are // broken into several values because of special characters like '"' // needed for the android code - this problem only exists in // Android xml library and not on the PC !! if (prop.hasChildNodes()) { // false for optional attributes StringBuilder text = new StringBuilder(); NodeList chars = prop.getChildNodes(); for (int k = 0; k < chars.getLength(); k++) { text.append(chars.item(k).getNodeValue()); }//from w ww . ja v a 2s .co m return text.toString().trim(); } else { return (""); // return empty string if empty } }
From source file:de.ingrid.portal.global.UtilsMapServiceManager.java
private static void evaluateKmlNode(HashMap data, Node node) { if (node.getNamespaceURI().equals(IDFNamespaceContext.NAMESPACE_URI_KML)) { Node documentNode = XPathUtils.getNode(node, "./kml:Document"); if (documentNode != null) { Node titleNode = XPathUtils.getNode(documentNode, "./kml:name"); String title = ""; // Titel if (titleNode != null) { title = titleNode.getTextContent().trim(); data.put("coord_class", title); }// w w w . j a v a 2s . c om //Placemark NodeList placemarkNodeList = XPathUtils.getNodeList(documentNode, "./kml:Placemark"); if (placemarkNodeList != null) { ArrayList<HashMap<String, String>> placemarks = new ArrayList<HashMap<String, String>>(); for (int i = 0; i < placemarkNodeList.getLength(); i++) { Node pmNode = placemarkNodeList.item(i); HashMap<String, String> placemark = new HashMap<String, String>(); placemark.put("coord_class", title); // Name Node pmNameNode = XPathUtils.getNode(pmNode, "./kml:name"); if (pmNameNode != null) { String name = pmNameNode.getTextContent().trim(); if (name != null) { placemark.put("coord_title", name); } } // Description Node pmDescrNode = XPathUtils.getNode(pmNode, "./kml:description"); if (pmDescrNode != null) { String description = pmDescrNode.getTextContent().trim(); if (description != null) { placemark.put("coord_descr", description); } } // Point Node pmPointNode = XPathUtils.getNode(pmNode, "./kml:Point"); if (pmPointNode != null) { if (pmPointNode.hasChildNodes()) { Node coordinatesNode = XPathUtils.getNode(pmPointNode, "./kml:coordinates"); if (coordinatesNode != null) { String coordinates = coordinatesNode.getTextContent().trim(); if (coordinates != null) { String[] coords = coordinates.split(","); placemark.put("coord_x", coords[0]); placemark.put("coord_y", coords[1]); } } } } placemarks.add(placemark); } data.put("placemarks", placemarks); } } } }
From source file:Main.java
/**Recursive method which has a side effect of setting the result to the pretty-printed flat text version of an XML node. * @param finger the current node//from ww w .j av a2 s .c o m * @param result the resultant string that is being built up. * @param indent the current indenting level. */ private static void doc2String(Node finger, StringBuffer result, int indent) { //Base Case for (int j = 0; j < indent; j++) result.append(' '); if (finger.getNodeType() == Node.TEXT_NODE) { result.append(finger.getNodeValue().trim()); result.append("\n"); return; } result.append('<'); //System.out.println("XMLUtils: appending " + finger.getNodeName() + " to output"); result.append(finger.getNodeName().trim()); result.append('>'); result.append("\n"); if (finger.hasChildNodes()) { NodeList childList = finger.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { doc2String(childList.item(i), result, indent + 1); } } for (int j = 0; j < indent; j++) result.append(' '); result.append("</"); //System.out.println("XMLUtils: appending end " + finger.getNodeName() + " to output"); result.append(finger.getNodeName().trim()); result.append('>'); result.append("\n"); }
From source file:com.flexive.shared.media.impl.FxMediaImageMagickEngine.java
/** * Identify a file, returning metadata/*from w w w .j a v a 2s . c o m*/ * * @param mimeType if not null it will be used to call the correct identify routine * @param file the file to identify * @return metadata * @throws FxApplicationException on errors * @since 3.1 */ public static FxMetadata identify(String mimeType, File file) throws FxApplicationException { if (mimeType == null) mimeType = FxMediaNativeEngine.detectMimeType(null, file.getAbsolutePath()); try { String metaData = IMParser.getMetaData(file); String format = "unknown"; String formatDescription = ""; String compressionAlgorithm = ""; String colorType = ""; int width = 0; int height = 0; double xRes = 0.0; double yRes = 0.0; int bpp = 0; DocumentBuilder builder = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(new ByteArrayInputStream(metaData.getBytes())); XPath xPath = javax.xml.xpath.XPathFactory.newInstance().newXPath(); Node nFormat = (Node) xPath.evaluate("/Image/Format", document, javax.xml.xpath.XPathConstants.NODE); if (nFormat != null && nFormat.getTextContent() != null) { format = nFormat.getTextContent(); if (format.indexOf(' ') > 0) { formatDescription = format.substring(format.indexOf(' ') + 1); if (formatDescription.indexOf('(') >= 0 && formatDescription.indexOf(')') > 0) { formatDescription = formatDescription.substring(formatDescription.indexOf('(') + 1, formatDescription.indexOf(')')); } format = format.substring(0, format.indexOf(' ')); } } Node nCompression = (org.w3c.dom.Node) xPath.evaluate("/Image/Compression", document, javax.xml.xpath.XPathConstants.NODE); if (nCompression != null && nCompression.getTextContent() != null) { compressionAlgorithm = nCompression.getTextContent(); } Node nColorType = (Node) xPath.evaluate("/Image/Colorspace", document, javax.xml.xpath.XPathConstants.NODE); if (nColorType != null && nColorType.getTextContent() != null) { colorType = nColorType.getTextContent(); } Node nGeometry = (Node) xPath.evaluate("/Image/Geometry", document, javax.xml.xpath.XPathConstants.NODE); if (nGeometry != null && nGeometry.getTextContent() != null) { String geo = nGeometry.getTextContent(); if (geo.indexOf('+') > 0) geo = geo.substring(0, geo.indexOf('+')); if (geo.indexOf('x') > 0) { try { width = Integer.parseInt(geo.substring(0, geo.indexOf('x'))); height = Integer.parseInt(geo.substring(geo.indexOf('x') + 1)); } catch (NumberFormatException ex) { //failed, ignore } } } Node nResolution = (Node) xPath.evaluate("/Image/Resolution", document, javax.xml.xpath.XPathConstants.NODE); if (nResolution != null && nResolution.getTextContent() != null) { String res = nResolution.getTextContent(); if (res.indexOf('+') > 0) res = res.substring(0, res.indexOf('+')); if (res.indexOf('x') > 0) { try { xRes = Double.parseDouble(res.substring(0, res.indexOf('x'))); yRes = Double.parseDouble(res.substring(res.indexOf('x') + 1)); } catch (NumberFormatException ex) { //failed, ignore } } } Node nDepth = (Node) xPath.evaluate("/Image/Depth", document, javax.xml.xpath.XPathConstants.NODE); if (nDepth != null && nDepth.getTextContent() != null) { String dep = nDepth.getTextContent(); if (dep.indexOf('-') > 0) dep = dep.substring(0, dep.indexOf('-')); try { bpp = Integer.parseInt(dep); } catch (NumberFormatException ex) { //failed, ignore } } List<FxMetadata.FxMetadataItem> items = new ArrayList<FxMetadata.FxMetadataItem>(50); NodeList nodes = (NodeList) xPath.evaluate("/Image/*", document, javax.xml.xpath.XPathConstants.NODESET); Node currNode; for (int i = 0; i < nodes.getLength(); i++) { currNode = nodes.item(i); if (currNode.hasChildNodes() && currNode.getChildNodes().getLength() > 1) { for (int j = 0; j < currNode.getChildNodes().getLength(); j++) items.add(new FxMetadata.FxMetadataItem( currNode.getNodeName() + "/" + currNode.getChildNodes().item(j).getNodeName(), currNode.getChildNodes().item(j).getTextContent())); } else items.add(new FxMetadata.FxMetadataItem(currNode.getNodeName(), currNode.getTextContent())); } return new FxImageMetadataImpl(mimeType, file.getName(), items, width, height, format, formatDescription, compressionAlgorithm, xRes, yRes, colorType, false, bpp, false, false, null); } catch (Exception e) { throw new FxApplicationException(e, "ex.media.identify.error", file.getName(), mimeType, e.getMessage()); } }