List of usage examples for org.w3c.dom Element getFirstChild
public Node getFirstChild();
From source file:Main.java
/** * Get the text content of an element identified by a path, * where the path elements can include an index. The first * path element must not have an index, and its name must * match the name of the starting node. If the starting * node is a Document, the root Element of the document is * used as the starting point. Path elements must be separated * by the slash character. If the path starts with a slash, * the slash is ignored. If the element or attribute identified * by the path is not present as a child of the starting node, * the empty string is returned. If a path element identifies * an attribute, any subsequent path elements are ignored. * A path is in the form: /e1/e2/e3/... or /e1/e2/@attr * Note the slash preceding the attribute's @-sign. * @param node the starting node for the path. The first path * element must match the name of this node. * @param path the path to the target node. * @return the full text value of the target node (including all * descendent text nodes), or the empty string if the target is * not a descendent of the starting node. */// w ww . j a v a 2s . c o m public static String getTextContent(Node node, String path) { if (node instanceof Document) node = ((Document) node).getDocumentElement(); if (!(node instanceof Element)) return ""; Element el = (Element) node; path = path.replaceAll("\\s", ""); if (path.startsWith("/")) path = path.substring(1); String[] pathElements = path.split("/"); if (!pathElements[0].equals(el.getTagName())) return ""; for (int i = 1; i < pathElements.length; i++) { String pe = pathElements[i]; if (pe.startsWith("@")) { //If this path element identifies an attribute, return it //and ignore any further path elements. return el.getAttribute(pe.substring(1)); } else { //This path element identifies an Element. It may have an index. //Get the index, if present, and get the element name. int n = 0; int k = pe.indexOf("["); int kk = pe.lastIndexOf("]"); if ((k != -1) && (k < kk)) { try { n = Integer.parseInt(pe.substring(k + 1, kk)); } catch (Exception ex) { return ""; } pe = pe.substring(0, k); } else if (k != kk) return ""; //We now have the element name and the index. //Find the identified Element. We have to count //matching elements to find the one identified //by the index. int nn = 0; Node child = el.getFirstChild(); while (child != null) { if ((child.getNodeType() == Node.ELEMENT_NODE) && child.getNodeName().equals(pe)) { if (n == nn) break; nn++; } child = child.getNextSibling(); } //If the child is null, we didn't find the identified Element. if (child == null) return ""; //If we get here, we found it, now look for the next one. el = (Element) child; } } //Okay, we must be at the end of the path, and it must be an Element. //Return the text content of the element. return el.getTextContent(); }
From source file:com.redhat.plugin.eap6.EAP6DeploymentStructureMojo.java
protected void buildDeploymentStructure(Document doc, Map<Artifact, String> moduleMap, List<SubDeployment> subdeployments) throws MojoFailureException, XPathExpressionException { Element root = doc.getDocumentElement(); if (!root.getTagName().equals("jboss-deployment-structure")) throw new MojoFailureException("Root element is not jboss-deployment-structure"); Element deployment = (Element) xp_deployment.evaluate(doc, XPathConstants.NODE); if (deployment == null) { deployment = doc.createElement("deployment"); root.insertBefore(deployment, root.getFirstChild()); }/*from w w w. jav a 2 s . com*/ Element depDependencies = (Element) xp_dependencies.evaluate(deployment, XPathConstants.NODE); if (depDependencies == null) { depDependencies = doc.createElement("dependencies"); deployment.appendChild(depDependencies); } Collection<String> mods = moduleMap.values(); getLog().debug("From project-dependencies" + mods); fillModuleEntries(doc, depDependencies, mods); getLog().debug("Element <" + depDependencies.getTagName() + ">: " + depDependencies.getChildNodes().getLength() + " elements"); if (subdeployments != null && !subdeployments.isEmpty()) { for (SubDeployment sd : subdeployments) { XPathExpression xp = xpf.newXPath() .compile("/jboss-deployment-structure/sub-deployment [@name='" + sd.getName() + "']"); Element subEl = (Element) xp.evaluate(doc, XPathConstants.NODE); if (subEl == null) { getLog().debug("Creating sub-deployment-section for <" + sd.getName() + ">"); subEl = doc.createElement("sub-deployment"); root.appendChild(subEl); subEl.setAttribute("name", sd.getName()); } Element subDependencies = (Element) xp_dependencies.evaluate(subEl, XPathConstants.NODE); if (subDependencies == null) { subDependencies = doc.createElement("dependencies"); subEl.appendChild(subDependencies); } Set<String> modules = new HashSet<String>(); xp = xpf.newXPath().compile("/jboss-deployment-structure/deployment/dependencies/module/@name"); NodeList nl = (NodeList) xp.evaluate(sd.getDocument(), XPathConstants.NODESET); int n = nl.getLength(); for (int i = 0; i < n; i++) { if (moduleMap.values().contains(nl.item(i).getTextContent())) continue; modules.add(nl.item(i).getTextContent()); } getLog().debug("From sub-deployment <" + sd.getName() + ">:" + modules); fillModuleEntries(doc, subDependencies, modules); getLog().debug("Child-Elements for <" + subEl.getAttribute("name") + ">: " + subEl.getChildNodes().getLength()); getLog().debug("Element <" + subEl.getTagName() + "." + subDependencies.getTagName() + ">: " + subDependencies.getChildNodes().getLength() + " elements"); } } NodeList nlSub = (NodeList) xp_subdeployment.evaluate(doc, XPathConstants.NODESET); int nSub = nlSub.getLength(); getLog().debug("Retrieved subdeployment-sections (" + nSub + ")"); }
From source file:com.verisign.epp.codec.gen.EPPUtil.java
/** * Decode <code>Integer</code>, by XML namespace and tag name, from an XML * Element. The children elements of <code>aElement</code> will be searched * for the specified <code>aNS</code> namespace URI and the specified * <code>aTagName</code>. The first XML element found will be decoded and * returned. If no element is found, <code>null</code> is returned. * /*from w w w. j av a2 s. c o m*/ * @param aElement * XML Element to scan. For example, the element could be * <domain:create> * @param aNS * XML namespace of the elements. For example, for domain element * this is "urn:iana:xmlns:domain". * @param aTagName * Tag name of the element including an optional namespace * prefix. For example, the tag name for the domain name is * "domain:name". * @return <code>Integer</code> value if found; <code>null</code> otherwise. * @exception EPPDecodeException * Error decoding <code>aElement</code>. */ public static Integer decodeInteger(Element aElement, String aNS, String aTagName) throws EPPDecodeException { Element theElm = EPPUtil.getElementByTagNameNS(aElement, aNS, aTagName); Integer retInteger = null; if (theElm != null) { Node textNode = theElm.getFirstChild(); // Element does have a text node? if (textNode != null) { String intValStr = textNode.getNodeValue(); try { retInteger = Integer.valueOf(intValStr); } catch (NumberFormatException e) { throw new EPPDecodeException("Can't convert value to Integer: " + intValStr + e); } } else { throw new EPPDecodeException("Can't decode numeric value from non-existant text node"); } } return retInteger; }
From source file:com.evolveum.midpoint.prism.util.JaxbTestUtil.java
public <T> Element marshalObjectToDom(T jaxbObject, QName elementQName, Document doc) throws JAXBException { if (doc == null) { doc = DOMUtil.getDocument();/* w w w . jav a 2 s . co m*/ } JAXBElement<T> jaxbElement = new JAXBElement<T>(elementQName, (Class<T>) jaxbObject.getClass(), jaxbObject); Element element = doc.createElementNS(elementQName.getNamespaceURI(), elementQName.getLocalPart()); marshalElementToDom(jaxbElement, element); return (Element) element.getFirstChild(); }
From source file:com.verisign.epp.codec.gen.EPPUtil.java
/** * Decode <code>BigDecimal</code>, by XML namespace and tag name, from an * XML Element. The children elements of <code>aElement</code> will be * searched for the specified <code>aNS</code> namespace URI and the * specified <code>aTagName</code>. The first XML element found will be * decoded and returned. If no element is found, <code>null</code> is * returned.//w w w . java 2 s . com * * @param aElement * XML Element to scan. For example, the element could be * <domain:create> * @param aNS * XML namespace of the elements. For example, for domain element * this is "urn:iana:xmlns:domain". * @param aTagName * Tag name of the element including an optional namespace * prefix. For example, the tag name for the domain name is * "domain:name". * @return <code>BigDecimal</code> value if found; <code>null</code> * otherwise. * @exception EPPDecodeException * Error decoding <code>aElement</code>. */ public static BigDecimal decodeBigDecimal(Element aElement, String aNS, String aTagName) throws EPPDecodeException { Element theElm = EPPUtil.getElementByTagNameNS(aElement, aNS, aTagName); BigDecimal retBigDecimal = null; if (theElm != null) { Node textNode = theElm.getFirstChild(); // Element does have a text node? if (textNode != null) { String doubleValStr = textNode.getNodeValue(); try { Double tempDouble = Double.valueOf(doubleValStr); retBigDecimal = new BigDecimal(tempDouble.doubleValue()); retBigDecimal = retBigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP); } catch (NumberFormatException e) { throw new EPPDecodeException("Can't convert value to Double: " + doubleValStr + e); } } else { throw new EPPDecodeException("Can't decode numeric value from non-existant text node"); } } return retBigDecimal; }
From source file:com.enonic.esl.xml.XMLTool.java
public static Element renameElement(Element elem, String newName) { Document doc = elem.getOwnerDocument(); // Create an element with the new name Element elem2 = doc.createElement(newName); // Copy the attributes to the new element NamedNodeMap attrs = elem.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Attr attr2 = (Attr) doc.importNode(attrs.item(i), true); elem2.getAttributes().setNamedItem(attr2); }/*from www. j av a 2 s . c o m*/ // Move all the children while (elem.hasChildNodes()) { elem2.appendChild(elem.getFirstChild()); } // Replace the old node with the new node elem.getParentNode().replaceChild(elem2, elem); return elem2; }
From source file:com.firegnom.valkyrie.map.tiled.TiledZoneLoader.java
/** * Gets the layer.//w w w . j ava 2s.c om * * @param map the map * @param element the element * @return the layer * @throws TiledLoaderException the tiled loader exception */ public Layer getLayer(Zone map, Element element) throws TiledLoaderException { // this.map = map; String name = element.getAttribute("name"); int width = Integer.parseInt(element.getAttribute("width")); int height = Integer.parseInt(element.getAttribute("height")); Layer l = new Layer(name, width, height); // data = new int[width][height][3]; // now read the layer properties Element propsElement = (Element) element.getElementsByTagName("properties").item(0); if (propsElement != null) { NodeList properties = propsElement.getElementsByTagName("property"); if (properties != null) { l.props = new Properties(); for (int p = 0; p < properties.getLength(); p++) { Element propElement = (Element) properties.item(p); String k = propElement.getAttribute("name"); String v = propElement.getAttribute("value"); l.props.setProperty(k, v); } } } Element dataNode = (Element) element.getElementsByTagName("data").item(0); String encoding = dataNode.getAttribute("encoding"); String compression = dataNode.getAttribute("compression"); long decodetime = 0, readTime = 0; if (encoding.equals("base64") && compression.equals("gzip")) { try { Node cdata = dataNode.getFirstChild(); char[] enc = cdata.getNodeValue().trim().toCharArray(); byte[] dec = Base64.decode(enc); GZIPInputStream is = new GZIPInputStream(new ByteArrayInputStream(dec)); byte[] r = new byte[height * width * 4]; int read = 0; while (read < height * width * 4) { read += is.read((byte[]) (r), read, height * width * 4 - read); } // Log.d("aadsdasdsa","data read :"+read+"more :"+is.available()); // //5072 // if (l.name.equals("Layer 2")){ // read = is.read((byte[])(r), read, height*width*4-read); // Log.d("aadsdasdsa","data read :"+read+"more :"+is.available()); // } int tileId, y, x; int pos = 0, tmp; StringTileSet set; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { tmp = 0; tmp |= ((int) (r[pos] & 0xFF)); tmp |= ((int) (r[pos + 1] & 0xFF)) << 8; tmp |= ((int) (r[pos + 2] & 0xFF)) << 16; tmp |= ((int) (r[pos + 3] & 0xFF)) << 24; tileId = tmp; l.data[x][y] = tileId; if (tileId != 0 && map.activeTiles.get(tileId) == null) { set = map.findTileSet(tileId); // rl.downloadService(set.getTileNamePng(tileId)); map.activeTiles.put(tileId, set.getTileNamePng(tileId)); } pos += 4; } } if (l.name.equals(Zone.MOVE_MATRIX)) { map.buildMoveMatrix(l); } return l; } catch (IOException e) { Log.e("error", e.toString()); throw new TiledLoaderException("Unable to decode base 64 block"); } } else { throw new TiledLoaderException( "Unsupport tiled map type: " + encoding + "," + compression + " (only gzip base64 supported)"); } }
From source file:com.evolveum.midpoint.prism.util.JaxbTestUtil.java
public <T> Element marshalElementToDom(JAXBElement<T> jaxbElement, Document doc) throws JAXBException { if (doc == null) { doc = DOMUtil.getDocument();/*from ww w. j a v a2s .co m*/ } Element element = doc.createElementNS(jaxbElement.getName().getNamespaceURI(), jaxbElement.getName().getLocalPart()); marshalElementToDom(jaxbElement, element); return (Element) element.getFirstChild(); }
From source file:com.waitwha.nessus.server.Server.java
/** * Executes the given HttpPost using a HttpClient. If 200 OK is returned, * we will parse the contents and return a ServerReply implementation. * //www.j a v a 2 s . c o m * @param post HttpPost to execute. * @return ServerReply */ public ServerReply getReply(HttpPost post) { ServerReply reply = null; HttpClient client = this.getClient(); try { log.finest(String.format("[%s] Executing POST.", post.getURI())); HttpResponse resp = client.execute(post); try { HttpEntity entity = resp.getEntity(); if (resp.getStatusLine().getStatusCode() == 200) { InputStream in = entity.getContent(); log.finest(String.format("[%s] Received HTTP code %d: %dbytes (%s)", post.getURI(), resp.getStatusLine().getStatusCode(), entity.getContentLength(), entity.getContentType().getValue())); Document document = this.builder.parse(in); Element replyElement = (Element) document.getFirstChild(); Element contents = ElementUtils.getFirstElementByName(replyElement, "contents"); /* * Test the first element found within the element 'contents'. If the * element's name is 'token', then this is a LoginReply. However, if the * name of the element is 'reports', this will mean this is a ReportListReply. * */ Element firstElement = (Element) contents.getFirstChild(); if (firstElement == null) reply = new ErrorReply(replyElement); else if (firstElement.getTagName().equals("reports")) reply = new ReportListReply(replyElement); else reply = new LoginReply(replyElement); log.finest(String.format("[%s] Parsed XML succcessfully: %s", post.getURI(), reply.getClass().getName())); } else { log.warning(String.format("[%s] Received HTTP code %d. Skipping parsing of content.", post.getURI(), resp.getStatusLine().getStatusCode())); EntityUtils.consume(entity); } } catch (IOException | SAXException | ElementNotFoundException e) { log.warning(String.format("Could read/parse reply from server %s: %s %s", this.url, e.getClass().getName(), e.getMessage())); } } catch (IOException e) { log.warning(String.format("Could not connect to server %s: %s", this.url, e.getMessage())); } return reply; }