List of usage examples for org.w3c.dom Node getNextSibling
public Node getNextSibling();
From source file:org.cleverbus.core.common.exception.AbstractSoapExceptionFilter.java
/** * Gets first child element (node with type {@link Node#ELEMENT_NODE}. * * @param node the node// w ww . ja va 2 s .co m * @return element */ protected Node getFirstElm(Node node) { node = node.getFirstChild(); while (node.getNodeType() != Node.ELEMENT_NODE) { node = node.getNextSibling(); } return node; }
From source file:de.betterform.xml.dom.DOMUtil.java
/** * __UNDOCUMENTED__// ww w . j a v a 2 s. co m * * @param newChild __UNDOCUMENTED__ * @param refChild __UNDOCUMENTED__ * @throws DOMException __UNDOCUMENTED__ */ public static void insertAfter(Node newChild, Node refChild) throws DOMException { if (refChild == null) { throw new DOMException(DOMException.NOT_FOUND_ERR, "refChild == null"); } Node nextSibling = refChild.getNextSibling(); if (nextSibling == null) { refChild.getParentNode().appendChild(newChild); } else { refChild.getParentNode().insertBefore(newChild, nextSibling); } }
From source file:com.cordys.coe.ac.httpconnector.samples.JIRAResponseHandler.java
/** * This method checks the HTML for errors during processing. * /*from w w w . j a va2 s . c o m*/ * @param document * The HTML document. * @param httpMethod * The actual HTTP method that was executed. * * @throws HandlerException * In case the response contains any functional errors. * @throws XPathExpressionException * In case one of the XPaths fail. */ protected void checkErrors(org.w3c.dom.Document document, HttpMethod httpMethod) throws HandlerException, XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xpath.evaluate("//span[@class='errMsg']/text()", document, XPathConstants.NODESET); int length = nodeList.getLength(); if (length != 0) { // The first error message found will be used. HandlerException he = new HandlerException( HandlerExceptionMessages.ERROR_CONVERTING_THE_RESPONSE_TO_PROPER_XML, nodeList.item(0).getNodeValue()); for (int i = 0; i < length; i++) { Node node = nodeList.item(i); he.addAdditionalErrorMessage(node.getNodeValue()); } throw he; } // There is another possibility of which errors might be returned. There // is a td with // class formErrors. And it that holds the errors as list items. nodeList = (NodeList) xpath.evaluate("//td[@class='formErrors']/div[@class='errorArea']/ul/li/text()", document, XPathConstants.NODESET); length = nodeList.getLength(); if (length != 0) { // The first error message found will be used. HandlerException he = new HandlerException( HandlerExceptionMessages.ERROR_CONVERTING_THE_RESPONSE_TO_PROPER_XML, nodeList.item(0).getNodeValue()); for (int i = 0; i < length; i++) { Node node = nodeList.item(i); he.addAdditionalErrorMessage(node.getNodeValue()); } throw he; } if (httpMethod.getStatusCode() == 500) { // Find the short description Node n = (Node) xpath.evaluate("//b[.='Cause: ']", document, XPathConstants.NODE); String shortError = n.getNextSibling().getNextSibling().getNodeValue().trim(); // The first error message found will be used. HandlerException he = new HandlerException( HandlerExceptionMessages.ERROR_CONVERTING_THE_RESPONSE_TO_PROPER_XML, "System Error: " + shortError); // Find the stacktrace if available. he.addAdditionalErrorMessage( (String) xpath.evaluate("//pre[@id='stacktrace']/text()", document, XPathConstants.STRING)); throw he; } }
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 a2 s .c o m*/ } printElement(child); child = child.getNextSibling(); } } }
From source file:playground.jbischoff.carsharing.data.VBBRouteCatcher.java
private void run(Coord from, Coord to, long departureTime) { Locale locale = new Locale("en", "UK"); String pattern = "###.000000"; DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(locale); df.applyPattern(pattern);// w w w.java2 s . c o m // Construct data //X&Y coordinates must be exactly 8 digits, otherwise no proper result is given. They are swapped (x = long, y = lat) //Verbindungen 1-n bekommen; Laufweg, Reisezeit & Umstiege ermitteln String text = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" + "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" + "<ReqC accessId=\"JBischoff2486b558356fa9b81b1rzum\" ver=\"1.1\" requestId=\"7\" prod=\"SPA\" lang=\"DE\">" + "<ConReq>" + "<ReqT date=\"" + VBBDAY.format(departureTime) + "\" time=\"" + VBBTIME.format(departureTime) + "\">" + "</ReqT>" + "<RFlags b=\"0\" f=\"1\" >" + "</RFlags>" + "<Start>" + "<Coord name=\"START\" x=\"" + df.format(from.getY()).replace(".", "") + "\" y=\"" + df.format(from.getX()).replace(".", "") + "\" type=\"WGS84\"/>" + "<Prod prod=\"1111000000000000\" direct=\"0\" sleeper=\"0\" couchette=\"0\" bike=\"0\"/>" + "</Start>" + "<Dest>" + "<Coord name=\"ZIEL\" x=\"" + df.format(to.getY()).replace(".", "") + "\" y=\"" + df.format(to.getX()).replace(".", "") + "\" type=\"WGS84\"/>" + "</Dest>" + "</ConReq>" + "</ReqC>"; PostMethod post = new PostMethod("http://demo.hafas.de/bin/pub/vbb/extxml.exe/"); post.setRequestBody(text); post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1"); HttpClient httpclient = new HttpClient(); try { int result = httpclient.executeMethod(post); // Display status code // System.out.println("Response status code: " + result); // Display response // System.out.println("Response body: "); // System.out.println(post.getResponseBodyAsString()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(post.getResponseBodyAsStream()); if (writeOutput) { BufferedWriter writer = IOUtils.getBufferedWriter(filename); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //initialize StreamResult with File object to save to file StreamResult res = new StreamResult(writer); DOMSource source = new DOMSource(document); transformer.transform(source, res); writer.flush(); writer.close(); } Node connectionList = document.getFirstChild().getFirstChild().getFirstChild(); NodeList connections = connectionList.getChildNodes(); int amount = connections.getLength(); for (int i = 0; i < amount; i++) { Node connection = connections.item(i); Node overview = connection.getFirstChild(); ; while (!overview.getNodeName().equals("Overview")) { overview = overview.getNextSibling(); } System.out.println(overview.getChildNodes().item(3).getTextContent()); int transfers = Integer.parseInt(overview.getChildNodes().item(3).getTextContent()); String time = overview.getChildNodes().item(4).getFirstChild().getTextContent().substring(3); System.out.println(time); Date rideTime = VBBDATE.parse(time); int seconds = rideTime.getHours() * 3600 + rideTime.getMinutes() * 60 + rideTime.getSeconds(); System.out.println(seconds + "s; transfers: " + transfers); if (seconds < this.bestRideTime) { this.bestRideTime = seconds; this.bestTransfers = transfers; } } } catch (Exception e) { this.bestRideTime = -1; this.bestTransfers = -1; } finally { // Release current connection to the connection pool // once you are done post.releaseConnection(); post.abort(); } }
From source file:XMLDocumentWriter.java
/** * Output the specified DOM Node object, printing it using the specified * indentation string/*from ww w .j a v a 2 s . c om*/ */ public void write(Node node, String indent) { // The output depends on the type of the node switch (node.getNodeType()) { case Node.DOCUMENT_NODE: { // If its a Document node Document doc = (Document) node; out.println(indent + "<?xml version='1.0'?>"); // Output header Node child = doc.getFirstChild(); // Get the first node while (child != null) { // Loop 'till no more nodes write(child, indent); // Output node child = child.getNextSibling(); // Get next node } break; } case Node.DOCUMENT_TYPE_NODE: { // It is a <!DOCTYPE> tag DocumentType doctype = (DocumentType) node; // Note that the DOM Level 1 does not give us information about // the the public or system ids of the doctype, so we can't output // a complete <!DOCTYPE> tag here. We can do better with Level 2. out.println("<!DOCTYPE " + doctype.getName() + ">"); break; } case Node.ELEMENT_NODE: { // Most nodes are Elements Element elt = (Element) node; out.print(indent + "<" + elt.getTagName()); // Begin start tag NamedNodeMap attrs = elt.getAttributes(); // Get attributes for (int i = 0; i < attrs.getLength(); i++) { // Loop through them Node a = attrs.item(i); out.print(" " + a.getNodeName() + "='" + // Print attr. name fixup(a.getNodeValue()) + "'"); // Print attr. value } out.println(">"); // Finish start tag String newindent = indent + " "; // Increase indent Node child = elt.getFirstChild(); // Get child while (child != null) { // Loop write(child, newindent); // Output child child = child.getNextSibling(); // Get next child } out.println(indent + "</" + // Output end tag elt.getTagName() + ">"); break; } case Node.TEXT_NODE: { // Plain text node Text textNode = (Text) node; String text = textNode.getData().trim(); // Strip off space if ((text != null) && text.length() > 0) // If non-empty out.println(indent + fixup(text)); // print text break; } case Node.PROCESSING_INSTRUCTION_NODE: { // Handle PI nodes ProcessingInstruction pi = (ProcessingInstruction) node; out.println(indent + "<?" + pi.getTarget() + " " + pi.getData() + "?>"); break; } case Node.ENTITY_REFERENCE_NODE: { // Handle entities out.println(indent + "&" + node.getNodeName() + ";"); break; } case Node.CDATA_SECTION_NODE: { // Output CDATA sections CDATASection cdata = (CDATASection) node; // Careful! Don't put a CDATA section in the program itself! out.println(indent + "<" + "![CDATA[" + cdata.getData() + "]]" + ">"); break; } case Node.COMMENT_NODE: { // Comments Comment c = (Comment) node; out.println(indent + "<!--" + c.getData() + "-->"); break; } default: // Hopefully, this won't happen too much! System.err.println("Ignoring node: " + node.getClass().getName()); break; } }
From source file:com.janoz.usenet.searchers.impl.NzbsOrgConnectorImpl.java
private List<NZB> fetchFeed(Collection<NameValuePair> params) throws SearchException, DOMException { THROTTLER.throttle();// ww w. j a v a 2s . com Document document = null; try { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.addAll(params); qparams.add(new BasicNameValuePair("dl", "1")); URI uri = getUri("rss.php", qparams); synchronized (builderSemaphore) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); DocumentBuilder builder = factory.newDocumentBuilder(); int attempts = RETRY_ATTEMPTS; boolean retry; do try { retry = false; document = builder.parse(uri.toString()); } catch (IOException ioe) { if (attempts == 0 || !ioe.getMessage().startsWith("Server returned HTTP response code: 503")) { throw ioe; } else { attempts--; retry = true; THROTTLER.throttleBig(); } } while (retry); } } catch (IOException ioe) { throw new SearchException("Error connecting to Nzbs.org.", ioe); } catch (SAXException se) { throw new SearchException("Error parsing rss from Nzbs.org.", se); } catch (ParserConfigurationException pce) { throw new SearchException("Error configuring XML parser.", pce); } catch (URISyntaxException e) { throw new SearchException("Error parsing URI.", e); } Node rss = document.getFirstChild(); if (!"rss".equalsIgnoreCase(rss.getNodeName())) { throw new SearchException("Result was not RSS but " + rss.getNodeName()); } Node channel = rss.getFirstChild(); while (channel != null && "#text".equals(channel.getNodeName())) { channel = channel.getNextSibling(); } NodeList list = channel.getChildNodes(); DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.CANADA); List<NZB> result = new ArrayList<NZB>(); UrlBasedSupplier supplier = new UrlBasedSupplier(); supplier.setThrottler(THROTTLER); for (int i = 0; i < list.getLength(); i++) { Node n = list.item(i); if ("item".equals(n.getNodeName())) { LazyNZB nzb = new LazyNZB("tmpName", supplier); try { for (int j = 0; j < n.getChildNodes().getLength(); j++) { Node n2 = n.getChildNodes().item(j); if ("title".equalsIgnoreCase(n2.getNodeName())) { nzb.setName(n2.getTextContent()); nzb.setFilename(Util.saveFileName(n2.getTextContent()) + ".nzb"); } if ("pubdate".equalsIgnoreCase(n2.getNodeName())) { nzb.setPostDate(df.parse(n2.getTextContent())); } if ("link".equalsIgnoreCase(n2.getNodeName())) { nzb.setUrl(n2.getTextContent()); } } result.add(nzb); } catch (ParseException e) { LOG.info("Skipping " + nzb.getName() + " because of date error.", e); } } } THROTTLER.setThrottleForNextAction(); return result; }
From source file:org.carewebframework.shell.BaseXmlParser.java
/** * Find the child element whose tag matches the specified tag name. * /* w w w .j a v a 2 s . co m*/ * @param tagName Tag name to locate. * @param element Parent element whose children are to be searched. * @return The matching node (first occurrence only) or null if not found. */ protected Element findTag(String tagName, Element element) { Node result = element.getFirstChild(); while (result != null) { if (result instanceof Element && (tagName.equals(((Element) result).getNodeName()) || tagName.equals(((Element) result).getLocalName()))) { break; } result = result.getNextSibling(); } return (Element) result; }
From source file:importer.handler.post.stages.Discriminator.java
/** * Are two elements next to each other?/*from w w w. j a va2 s . co m*/ * @param s1 the LHS element * @param s2 the RHS element * @return true if s1 is just before s2 */ boolean areAdjacent(Element s1, Element s2) { Node n = s1; while (n != null) { n = n.getNextSibling(); if (n != null) { if (n.getNodeType() == Node.ELEMENT_NODE) { if (n == s2) return true; } else if (n.getNodeType() == Node.TEXT_NODE) { if (!isWhitespace(n.getTextContent())) break; } } } return false; }
From source file:com.amalto.core.history.accessor.ManyFieldAccessor.java
public void create() { parent.create();/* w w w.ja v a2 s . com*/ // TODO Refactor this Document domDocument = document.asDOM(); Node node = getCollectionItemNode(); if (node == null) { Element parentNode = (Element) parent.getNode(); NodeList children = parentNode.getElementsByTagName(fieldName); int currentCollectionSize = children.getLength(); if (currentCollectionSize > 0) { Node refNode = children.item(currentCollectionSize - 1).getNextSibling(); while (currentCollectionSize <= index) { node = domDocument.createElementNS(domDocument.getNamespaceURI(), fieldName); parentNode.insertBefore(node, refNode); currentCollectionSize++; } } else { // Collection is not present at all, append at the end of parent element. Node lastAccessedNode = document.getLastAccessedNode(); if (lastAccessedNode != null) { Node refNode = lastAccessedNode.getNextSibling(); while (refNode != null && !(refNode instanceof Element)) { refNode = refNode.getNextSibling(); } while (currentCollectionSize <= index) { node = domDocument.createElementNS(domDocument.getNamespaceURI(), fieldName); if (lastAccessedNode == parentNode) { if (lastAccessedNode == document.asDOM().getDocumentElement() && lastAccessedNode.getChildNodes().getLength() > 0) parentNode.insertBefore(node, parentNode.getFirstChild()); else parentNode.appendChild(node); } else if (refNode != null && refNode.getParentNode() == parentNode) { parentNode.insertBefore(node, refNode); } else { parentNode.appendChild(node); } currentCollectionSize++; } } else { while (currentCollectionSize <= index) { node = domDocument.createElementNS(domDocument.getNamespaceURI(), fieldName); parentNode.appendChild(node); currentCollectionSize++; } } } document.setLastAccessedNode(node); } else if (node.getChildNodes().getLength() == 0) { // This accessor creates (n-1) empty elements when accessing first collection element at index n. // This setLastAccessedNode call allows all (n-1) elements to find their parent. if (!(node.getLocalName().equals(document.getLastAccessedNode().getLocalName()) && document.getLastAccessedNode().getParentNode() == node.getParentNode())) { // if last accessed node is parallel with this node, can't modify last accessed node. eg, last accessed // node=/feature/vendor[2], this node=/feature/vendor[1], the last accessed is still /feature/vendor[2] document.setLastAccessedNode(node); } } }