List of usage examples for org.w3c.dom Document getElementsByTagName
public NodeList getElementsByTagName(String tagname);
NodeList
of all the Elements
in document order with a given tag name and are contained in the document. From source file:it.unitn.disi.smatch.webapi.model.JSONHelper.java
public static JSONObject getJsonFromXml(Document doc) throws JSONException { NodeList list = doc.getElementsByTagName(TAG_JSON_DATA); JSONObject obj = null;// w w w .j ava 2 s .c o m if (list.getLength() > 0) { obj = new JSONObject(list.item(0).getTextContent()); } return obj; }
From source file:CB_Core.GCVote.GCVote.java
public static ArrayList<RatingData> GetRating(String User, String password, ArrayList<String> Waypoints) { ArrayList<RatingData> result = new ArrayList<RatingData>(); String data = "userName=" + User + "&password=" + password + "&waypoints="; for (int i = 0; i < Waypoints.size(); i++) { data += Waypoints.get(i);/*w w w. jav a 2 s . c o m*/ if (i < (Waypoints.size() - 1)) data += ","; } try { HttpPost httppost = new HttpPost("http://gcvote.de/getVotes.php"); httppost.setEntity(new ByteArrayEntity(data.getBytes("UTF8"))); // Log.info(log, "GCVOTE-Post" + data); // Execute HTTP Post Request String responseString = Execute(httppost); // Log.info(log, "GCVOTE-Response" + responseString); DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(responseString)); Document doc = db.parse(is); NodeList nodelist = doc.getElementsByTagName("vote"); for (Integer i = 0; i < nodelist.getLength(); i++) { Node node = nodelist.item(i); RatingData ratingData = new RatingData(); ratingData.Rating = Float.valueOf(node.getAttributes().getNamedItem("voteAvg").getNodeValue()); String userVote = node.getAttributes().getNamedItem("voteUser").getNodeValue(); ratingData.Vote = (userVote == "") ? 0 : Float.valueOf(userVote); ratingData.Waypoint = node.getAttributes().getNamedItem("waypoint").getNodeValue(); result.add(ratingData); } } catch (Exception e) { String Ex = ""; if (e != null) { if (e != null && e.getMessage() != null) Ex = "Ex = [" + e.getMessage() + "]"; else if (e != null && e.getLocalizedMessage() != null) Ex = "Ex = [" + e.getLocalizedMessage() + "]"; else Ex = "Ex = [" + e.toString() + "]"; } Log.err(log, "GcVote-Error" + Ex); return null; } return result; }
From source file:Main.java
public static boolean creteEntity(Object entity, String fileName) { boolean flag = false; try {/*w w w . j a v a 2 s. co m*/ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(fileName); Class clazz = entity.getClass(); Field[] fields = clazz.getDeclaredFields(); Node EntityElement = document.getElementsByTagName(clazz.getSimpleName() + "s").item(0); Element newEntity = document.createElement(clazz.getSimpleName()); EntityElement.appendChild(newEntity); for (Field field : fields) { field.setAccessible(true); Element element = document.createElement(field.getName()); element.appendChild(document.createTextNode(field.get(entity).toString())); newEntity.appendChild(element); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource domSource = new DOMSource(document); StreamResult streamResult = new StreamResult(new File(fileName)); transformer.transform(domSource, streamResult); flag = true; } catch (ParserConfigurationException pce) { System.out.println(pce.getLocalizedMessage()); pce.printStackTrace(); } catch (TransformerException te) { System.out.println(te.getLocalizedMessage()); te.printStackTrace(); } catch (IOException ioe) { System.out.println(ioe.getLocalizedMessage()); ioe.printStackTrace(); } catch (SAXException sae) { System.out.println(sae.getLocalizedMessage()); sae.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return flag; }
From source file:Main.java
/** * Get the list of all the first level elements of a document. * @param document the document object/*from w w w. j a v a 2 s . co m*/ * @param elementName the name of the element * @return the list of the elements */ public static List<Element> getElementsByTagName(final Document document, final String elementName) { if (elementName == null || document == null) { return null; } final NodeList nStepsList = document.getElementsByTagName(elementName); if (nStepsList == null) { return null; } final List<Element> result = new ArrayList<>(); for (int i = 0; i < nStepsList.getLength(); i++) { final Node node = nStepsList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { result.add((Element) node); } } return result; }
From source file:cz.muni.fi.webmias.TeXConverter.java
/** * Converts TeX formula to MathML using LaTeXML through a web service. * * @param query String containing one or more keywords and TeX formulae * (formulae enclosed in $ or $$).// w ww. j av a 2 s. c om * @return String containing formulae converted to MathML that replaced * original TeX forms. Non math tokens are connected at the end. */ public static String convertTexLatexML(String query) { query = query.replaceAll("\\$\\$", "\\$"); if (query.matches(".*\\$.+\\$.*")) { try { HttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(LATEX_TO_XHTML_CONVERSION_WS_URL); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<>(1); params.add(new BasicNameValuePair("code", query)); httppost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8)); // Execute and get the response. HttpResponse response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { try (InputStream responseContents = resEntity.getContent()) { DocumentBuilder dBuilder = MIaSUtils.prepareDocumentBuilder(); org.w3c.dom.Document doc = dBuilder.parse(responseContents); NodeList ps = doc.getElementsByTagName("p"); String convertedMath = ""; for (int k = 0; k < ps.getLength(); k++) { Node p = ps.item(k); NodeList pContents = p.getChildNodes(); for (int j = 0; j < pContents.getLength(); j++) { Node pContent = pContents.item(j); if (pContent instanceof Text) { convertedMath += pContent.getNodeValue() + "\n"; } else { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); StringWriter buffer = new StringWriter(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(pContent), new StreamResult(buffer)); convertedMath += buffer.toString() + "\n"; } } } return convertedMath; } } } } catch (TransformerException | SAXException | ParserConfigurationException | IOException ex) { Logger.getLogger(ProcessServlet.class.getName()).log(Level.SEVERE, null, ex); } } return query; }
From source file:Main.java
public static Element findNode(Document document, String nodeName) { if (document == null) throw new NullPointerException("Document cannot be null!"); if (nodeName == null) throw new NullPointerException("Nodename cannot be null!"); NodeList nodes = document.getElementsByTagName(nodeName); if (nodes == null || nodes.getLength() == 0) return null; if (nodes.getLength() > 1) throw new RuntimeException(nodes.getLength() + " nodes found where only 1 was expected"); return (Element) nodes.item(0); }
From source file:com.obidea.semantika.app.ApplicationFactory.java
private static NodeList getElementsByTagName(Document doc, String elementName) { return doc.getElementsByTagName(elementName); }
From source file:com.alta189.cyborg.commit.ShortUrlService.java
public static String shorten(String url, String keyword) { switch (service) { case BIT_LY://from w w w .j a v a2 s . co m HttpClient httpclient = new HttpClient(); HttpMethod method = new GetMethod("http://api.bit.ly/shorten"); method.setQueryString( new NameValuePair[] { new NameValuePair("longUrl", url), new NameValuePair("version", "2.0.1"), new NameValuePair("login", user), new NameValuePair("apiKey", apiKey), new NameValuePair("format", "xml"), new NameValuePair("history", "1") }); try { httpclient.executeMethod(method); String responseXml = method.getResponseBodyAsString(); String retVal = null; if (responseXml != null) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); StringReader st = new StringReader(responseXml); Document d = db.parse(new InputSource(st)); NodeList nl = d.getElementsByTagName("shortUrl"); if (nl != null) { Node n = nl.item(0); retVal = n.getTextContent(); } } return retVal; } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return null; case SPOUT_IN: HttpClient client = new HttpClient(); String result = null; client.getParams().setParameter("http.useragent", "Test Client"); BufferedReader br = null; PostMethod pMethod = new PostMethod("http://spout.in/yourls-api.php"); pMethod.addParameter("signature", apiKey); pMethod.addParameter("action", "shorturl"); pMethod.addParameter("format", "simple"); pMethod.addParameter("url", url); if (keyword != null) { pMethod.addParameter("keyword", keyword); } try { int returnCode = client.executeMethod(pMethod); if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) { System.err.println("The Post method is not implemented by this URI"); pMethod.getResponseBodyAsString(); } else { br = new BufferedReader(new InputStreamReader(pMethod.getResponseBodyAsStream())); String readLine; if (((readLine = br.readLine()) != null)) { result = readLine; } } } catch (Exception e) { System.err.println(e); } finally { pMethod.releaseConnection(); if (br != null) { try { br.close(); } catch (Exception fe) { fe.printStackTrace(); } } } return result; } return null; }
From source file:com.cisco.dvbu.ps.common.adapters.util.XmlUtils.java
public static String getNodeIterationValue(String tagName, String doc) throws Exception { String value = null;/*from ww w . j a v a 2 s .com*/ try { // Convert string to a DOM object Document docXML = stringToDocument(doc); NodeList node1 = docXML.getElementsByTagName(tagName); if (node1 != null && node1.item(0) != null) { for (int i = 0; i < node1.getLength(); i++) { NodeList node2 = node1.item(i).getChildNodes(); if (node2 != null && node2.item(0) != null) { for (int j = 0; j < node2.getLength(); j++) { Node n = node2.item(j); System.out.println("name=" + n.getNodeName() + " value=" + n.getTextContent()); } } } } } catch (Exception e) { throw e; } return value; }
From source file:org.earthtime.archivingTools.IEDACredentialsValidator.java
public static String validateSesarCredentials(String username, String password, boolean isVerbose) { String sesarCredentialsService = "http://app.geosamples.org/webservices/credentials_service.php";//note test http://sesar3.geoinfogeochem.org/webservices/credentials_service.php boolean valid = false; // Feb 2015 userCode is prefix for IGSN String userCode = ""; // using geochron as identifier since both are same and need backward compartibility for serialization ReduxPersistentState myState = ReduxPersistentState.getExistingPersistentState(); myState.getReduxPreferences().setGeochronUserName(username); myState.getReduxPreferences().setGeochronPassWord(password); myState.serializeSelf();/* ww w. j a v a 2 s .com*/ Document doc = HTTP_PostAndResponse(username, password, sesarCredentialsService); if (doc != null) { if (doc.getElementsByTagName("valid").getLength() > 0) { valid = doc.getElementsByTagName("valid").item(0).getTextContent().trim().equalsIgnoreCase("yes"); if (valid) { userCode = doc.getElementsByTagName("user_code").item(0).getTextContent().trim(); } } if (isVerbose) { JOptionPane.showMessageDialog(null, new String[] { valid ? "SESAR credentials are VALID!\n" : "SESAR credentials NOT valid!\n" }); } } else { if (isVerbose) { JOptionPane.showMessageDialog(null, new String[] { "SESAR Credentials Server " + sesarCredentialsService + " cannot be located.\n" }); } } return userCode; }