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:com.isa.ws.utiles.UtilesSWHelper.java
public static String getNodeValue(String xml, String node) { //get the factory DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try {//from w w w . ja v a2s . co m //Using factory get an instance of document builder DocumentBuilder db = dbf.newDocumentBuilder(); //parse using builder to get DOM representation of the XML file InputStream is = new ByteArrayInputStream(xml.getBytes()); Document dom = db.parse(is); NodeList nodelist = dom.getElementsByTagName(node); Node node1 = nodelist.item(0); String value = null; if (node1.getFirstChild() != null) { if (node.equals("css:validity")) { value = ""; value += node1.getChildNodes().item(0).getFirstChild().getNodeValue(); value += ","; value += node1.getChildNodes().item(1).getFirstChild().getNodeValue(); } else value = node1.getFirstChild().getNodeValue(); } return value; } catch (ParserConfigurationException pce) { pce.printStackTrace(); return null; } catch (SAXException se) { se.printStackTrace(); return null; } catch (IOException ioe) { ioe.printStackTrace(); return null; } }
From source file:com.microsoftopentechnologies.windowsazurestorage.helper.CredentialMigration.java
protected static List<StorageAccountInfo> getOldStorageConfig(File inputFile) throws SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); // Load the legacy storage config XML document, parse it and return a list of storage accounts Document document = builder.parse(inputFile); List<StorageAccountInfo> storages = new ArrayList<StorageAccountInfo>(); NodeList nodeList = document .getElementsByTagName("com.microsoftopentechnologies.windowsazurestorage.beans.StorageAccountInfo"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element elem = (Element) node; // Get the value of all sub-elements. String accName = elem.getElementsByTagName("storageAccName").item(0).getChildNodes().item(0) .getNodeValue();// w ww. jav a 2 s . c om String accKey = elem.getElementsByTagName("storageAccountKey").item(0).getChildNodes().item(0) .getNodeValue(); String blobURL = elem.getElementsByTagName("blobEndPointURL").item(0).getChildNodes().item(0) .getNodeValue(); storages.add(new StorageAccountInfo(accName, accKey, blobURL)); } } return storages; }
From source file:eu.serco.dhus.xml.parser.TaskTableParser.java
public static TaskTable parseTaskTable(String filename) throws ParserConfigurationException, SAXException, IOException { TaskTable taskTable = new TaskTable(); if (filename == null || filename.isEmpty()) throw new RuntimeException("The name of the XML file is required!"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); // Load the input XML document, parse it and return an instance of the // Document class. Document document = builder.parse(new File(filename)); document.getDocumentElement().normalize(); NodeList list = document.getElementsByTagName("Processor_Name"); logger.info(" NodeList list size----: " + list.getLength()); if (list != null && list.item(0) != null && list.item(0).getFirstChild() != null) { taskTable.setProcessorName(list.item(0).getFirstChild().getNodeValue()); }/*from w w w . java2s . c om*/ NodeList nodeList = document.getElementsByTagName("Task"); Node node; Element elem; List<Task> tasks = new ArrayList<Task>(); for (int i = 0; i < nodeList.getLength(); i++) { Task task = new Task(); node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { elem = (Element) node; task.setName(elem.getElementsByTagName("Name").item(0).getChildNodes().item(0).getNodeValue()); logger.info("taskname: " + task.getName()); List<Input> task_inputs = new ArrayList<Input>(); NodeList inputs = elem.getElementsByTagName("Input"); for (int j = 0; j < inputs.getLength(); j++) { Input input = new Input(); node = inputs.item(j); if (node.getNodeType() == Node.ELEMENT_NODE) { elem = (Element) node; input.setMode( elem.getElementsByTagName("Mode").item(0).getChildNodes().item(0).getNodeValue()); logger.info("==== mode: " + input.getMode()); input.setMandatory(elem.getElementsByTagName("Mandatory").item(0).getChildNodes().item(0) .getNodeValue()); logger.info("==== mandatory: " + input.getMandatory()); List<Alternative> input_alternatives = new ArrayList<Alternative>(); NodeList alternatives = elem.getElementsByTagName("Alternative"); for (int k = 0; k < alternatives.getLength(); k++) { Alternative alternative = new Alternative(); node = alternatives.item(k); if (node.getNodeType() == Node.ELEMENT_NODE) { elem = (Element) node; alternative.setOrder(Integer.parseInt(elem.getElementsByTagName("Order").item(0) .getChildNodes().item(0).getNodeValue())); logger.info("==== order: " + alternative.getOrder()); alternative.setRetrievalMode(elem.getElementsByTagName("Retrieval_Mode").item(0) .getChildNodes().item(0).getNodeValue()); logger.info("==== retrievalMode: " + alternative.getRetrievalMode()); alternative.setT0(Double.parseDouble(elem.getElementsByTagName("T0").item(0) .getChildNodes().item(0).getNodeValue())); logger.info("==== t0: " + alternative.getT0()); alternative.setT1(Double.parseDouble(elem.getElementsByTagName("T1").item(0) .getChildNodes().item(0).getNodeValue())); logger.info("==== t1: " + alternative.getT1()); alternative.setFileType(elem.getElementsByTagName("File_Type").item(0) .getChildNodes().item(0).getNodeValue()); logger.info("==== fileType: " + alternative.getFileType()); alternative.setFileNameType(elem.getElementsByTagName("File_Name_Type").item(0) .getChildNodes().item(0).getNodeValue()); logger.info("==== fileNameType: " + alternative.getFileNameType()); } input_alternatives.add(alternative); } input.setAlternatives(input_alternatives); } task_inputs.add(input); } task.setInputs(task_inputs); } tasks.add(task); } taskTable.setTasks(tasks); return taskTable; }
From source file:LVCoref.MMAX2.java
public static Boolean addMmaxNeAnnotation(Document d, String annotation_filename) { try {/*from w w w . j a v a 2s . c om*/ File mmax_file = new File(annotation_filename); DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); org.w3c.dom.Document doc = dBuilder.parse(mmax_file); NodeList markables = doc.getElementsByTagName("markable"); for (int i = 0; i < markables.getLength(); i++) { org.w3c.dom.Node markable = markables.item(i); String span = markable.getAttributes().getNamedItem("span").getNodeValue(); String category = markable.getAttributes().getNamedItem("category").getNodeValue(); String[] intervals = span.split(","); String[] interval = intervals[0].split("\\.\\."); int start = Integer.parseInt(interval[0].substring(5)) - 1; int end = start; if (interval.length > 1) { end = Integer.parseInt(interval[1].substring(5)) - 1; } //System.err.println(i+" :" + start+ "-"+end); // if (category.equals("profession")) category = "person"; // if (category.equals("event")) continue; // //if (category.equals("product")) continue; // if (category.equals("media")) continue; // if (category.equals("time")) continue; // if (category.equals("sum")) continue; if (category.equals("other")) continue; if (d.getNode(start).ne_annotation.length() != 0 || d.getNode(start).ne_annotation.length() != 0) continue; //if (d.getNode(start).isProperByFirstLetter()) { for (int j = start; j <= end; j++) { //System.out.println(j); Node q = d.getNode(j); q.ne_annotation = category; } //} } } catch (Exception e) { System.err.println("Error adding MMAX2 annotation:" + e.getMessage()); return false; } return true; }
From source file:com.AA.Other.RSSParse.java
/** * Get the list of articles currently contained in the RSS feed. * @param isBackground if the request is being run in the background * @param callingContext current application context * @return List of articles contained in the RSS on success. * On failure returns null// w w w .j a v a2s. co m */ public static List<Article> getArticles(boolean isBackground, Context callingContext) { //verify that we can use the network if (!isNetworkAvailable(isBackground, callingContext)) return null; //try and get the document Document doc = getDocument(); if (doc == null) return null; //parse into new articles try { ArrayList<Article> articles = new ArrayList<Article>(); NodeList items = doc.getElementsByTagName("item"); for (int i = 0; i < items.getLength(); i++) { //this cast _shoud_ be safe if the data is well formed Element el = (Element) items.item(i); //these also should be safe provided the data is well formed String title = el.getElementsByTagName("title").item(0).getFirstChild().getNodeValue(); String date = el.getElementsByTagName("pubDate").item(0).getFirstChild().getNodeValue(); String url = el.getElementsByTagName("link").item(0).getFirstChild().getNodeValue(); String desc = el.getElementsByTagName("description").item(0).getFirstChild().getNodeValue(); articles.add(new Article(desc, title, date, url)); } return articles; } catch (Exception e) { //any parse errors and we'll log and fail Log.e("AARSS", "Error Parsing RSS", e); return null; } }
From source file:uk.ac.bbsrc.tgac.miso.core.util.TaxonomyUtils.java
public static String checkScientificNameAtNCBI(String scientificName) { try {/*w w w. j a v a 2 s.c o m*/ String query = ncbiEntrezUtilsURL + "db=taxonomy&term=" + URLEncoder.encode(scientificName, "UTF-8"); final HttpClient httpclient = HttpClientBuilder.create().build(); HttpGet httpget = new HttpGet(query); try { HttpResponse response = httpclient.execute(httpget); String out = parseEntity(response.getEntity()); log.info(out); try { DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document d = docBuilder.newDocument(); TransformerFactory.newInstance().newTransformer() .transform(new StreamSource(new UnicodeReader(out)), new DOMResult(d)); NodeList nl = d.getElementsByTagName("Id"); for (int i = 0; i < nl.getLength(); i++) { Element e = (Element) nl.item(i); return e.getTextContent(); } } catch (ParserConfigurationException e) { log.error("check scientific name at NCBI", e); } catch (TransformerException e) { log.error("check scientific name at NCBI", e); } } catch (ClientProtocolException e) { log.error("check scientific name at NCBI", e); } catch (IOException e) { log.error("check scientific name at NCBI", e); } } catch (UnsupportedEncodingException e) { log.error("check scientific name at NCBI", e); } return null; }
From source file:Main.java
/** * Update a property of a given configuration file and return a string representation of the * xml document//from w ww. ja v a 2s . c o m * @param doc * @param property * @param newValue * @throws IllegalAccessException * @throws InstantiationException * @throws ClassNotFoundException */ public static String updateXmlDoc(Document doc, List<String> properties) throws ClassNotFoundException, InstantiationException, IllegalAccessException { for (String property : properties) { String key = property.split(":")[0]; String value = property.split(":")[1]; NodeList propertiesNode = doc.getElementsByTagName("esf:property"); for (int i = 0; i < propertiesNode.getLength(); i++) { Node node = propertiesNode.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element el = (Element) node; if (key.equals(el.getAttribute("name"))) { el.getElementsByTagName("esf:value").item(0).setTextContent(value); } } } } return parseXmlDocToString(doc); }
From source file:Main.java
/** * Returns an element parent node with "name" attribute based on a complex * key filter (parent.child.child)/*from ww w . j a v a 2 s. co m*/ * @param xsdDoc * @param xsdKey * @return */ protected static Element getXsdParentComplexKey(Document xsdDoc, String xsdKey) { Element tmpRes = null; Element element = null; String[] splitStr = xsdKey.split("[.]"); String topParent = splitStr[0]; String Parent = splitStr[1]; String Node = splitStr[2]; try { NodeList allNodes = xsdDoc.getElementsByTagName("*"); for (int i = 0; i < allNodes.getLength(); i++) { element = (Element) allNodes.item(i); if (element.getAttribute("name").equals(Node)) { element = (Element) element.getParentNode(); while (!((Element) element).hasAttribute("name")) { element = (Element) element.getParentNode(); } if (element.getAttribute("name").equals(Parent)) { Element pElement = (Element) element.getParentNode(); while (!((Element) pElement).hasAttribute("name")) { pElement = (Element) pElement.getParentNode(); } if (pElement.getAttribute("name").equals(topParent)) { tmpRes = element; } } } } return tmpRes; } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:com.emc.cto.ridagent.rid.test.TestScript.java
public static String httpSend(String output, String destURL) throws ParserConfigurationException, SAXException { /* Set up TLS mutual authentication */ KeyStore keystore = null;//from w ww.jav a2s .com String docid = null; try { keystore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } InputStream keystoreInput = null; try { keystoreInput = new FileInputStream(m_keystorePath); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { keystore.load(keystoreInput, m_keystorePassword.toCharArray()); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (logger.isDebugEnabled()) { logger.debug("Keystore has " + keystore.size() + " keys"); } } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } KeyStore truststore = null; try { truststore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } InputStream truststoreInput = null; try { truststoreInput = new FileInputStream(m_truststorePath); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { truststore.load(truststoreInput, m_truststorePassword.toCharArray()); } catch (NoSuchAlgorithmException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (CertificateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } SchemeRegistry schemeRegistry = new SchemeRegistry(); SSLSocketFactory schemeSocketFactory = null; try { schemeSocketFactory = new SSLSocketFactory(keystore, m_keystorePassword, truststore); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } schemeRegistry.register(new Scheme(m_protocol, m_port, schemeSocketFactory)); final HttpParams httpParams = new BasicHttpParams(); DefaultHttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(schemeRegistry), httpParams); /* Prepare the request to send */ Map<String, Object> responseMap = new HashMap<String, Object>(); HttpEntity request = new StringEntity(output, ContentType.TEXT_XML); //Create POST method HttpPost postMethod = new HttpPost(destURL); postMethod.setHeader("User-Agent", "EMC RID System"); postMethod.setHeader("Content-Type", "text/xml"); postMethod.setEntity(request); /* POST the request and process the response */ HttpResponse httpResponse = null; int code; try { httpResponse = httpClient.execute(postMethod); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (httpResponse.getEntity() != null) { code = httpResponse.getStatusLine().getStatusCode(); try { InputStream xml = httpResponse.getEntity().getContent(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(xml); docid = doc.getElementsByTagName("iodef:IncidentID").item(0).getTextContent(); System.out.println("ID of the newly created document " + docid); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } responseMap.put("success", true); responseMap.put("statusCode", code); } else { responseMap.put("success", false); responseMap.put("errorMessage", "Send failed (fill in exception)"); } return docid; }
From source file:Main.java
public static String getAttribute(String xmlStr, String tagName, String attrName) { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(false); // never forget this! Document doc = null; DocumentBuilder builder = null; String value = null;/* ww w. ja va2 s . c o m*/ try { builder = domFactory.newDocumentBuilder(); doc = builder.parse(new ByteArrayInputStream(xmlStr.getBytes())); // Get the root element Node rootNode = doc.getFirstChild(); NodeList nodeList = doc.getElementsByTagName(tagName); if ((nodeList.getLength() == 0) || (nodeList.item(0).getAttributes().getNamedItem(attrName) == null)) { logger.error("Either node " + tagName + " or attribute " + attrName + " not found."); } else { value = nodeList.item(0).getAttributes().getNamedItem(attrName).getNodeValue(); logger.debug("value of " + tagName + " attribute: " + attrName + " = " + value); } } catch (Exception ex) { System.out.println(ex.getMessage()); } return value; }