Example usage for org.w3c.dom Document getElementsByTagName

List of usage examples for org.w3c.dom Document getElementsByTagName

Introduction

In this page you can find the example usage for org.w3c.dom Document getElementsByTagName.

Prototype

public NodeList getElementsByTagName(String tagname);

Source Link

Document

Returns a NodeList of all the Elements in document order with a given tag name and are contained in the document.

Usage

From source file:com.commonsware.android.internet.WeatherDemo.java

void buildForecasts(String raw) throws Exception {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(raw)));
    NodeList times = doc.getElementsByTagName("start-valid-time");

    for (int i = 0; i < times.getLength(); i++) {
        Element time = (Element) times.item(i);
        Forecast forecast = new Forecast();

        forecasts.add(forecast);//  w w  w  .j a va  2s  .c o m
        forecast.setTime(time.getFirstChild().getNodeValue());
    }

    NodeList temps = doc.getElementsByTagName("value");

    for (int i = 0; i < temps.getLength(); i++) {
        Element temp = (Element) temps.item(i);
        Forecast forecast = forecasts.get(i);

        forecast.setTemp(new Integer(temp.getFirstChild().getNodeValue()));
    }

    NodeList icons = doc.getElementsByTagName("icon-link");

    for (int i = 0; i < icons.getLength(); i++) {
        Element icon = (Element) icons.item(i);
        Forecast forecast = forecasts.get(i);

        forecast.setIcon(icon.getFirstChild().getNodeValue());
    }
}

From source file:edu.wisc.my.portlets.bookmarks.domain.CollectionFolder.java

/**
 * Returns an immutable sorted view of the values of the children Map. The sorting is done
 * using the current childComparator. Warning, this is has a time cost of 2n log(n)
 * on every call./*from  www. ja v  a  2s.c o m*/
 * 
 * @return An immutable sorted view of the folder's children.
 */
public List<Entry> getSortedChildren() {
    List<Entry> children = new ArrayList<Entry>();
    log.debug("children: " + children.size());

    HttpClient client = new HttpClient();
    GetMethod get = null;

    try {

        log.debug("getting url " + url);
        get = new GetMethod(url);
        int rc = client.executeMethod(get);
        if (rc != HttpStatus.SC_OK) {
            log.error("HttpStatus:" + rc);
        }

        DocumentBuilderFactory domBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = domBuilderFactory.newDocumentBuilder();

        InputStream in = get.getResponseBodyAsStream();
        builder = domBuilderFactory.newDocumentBuilder();
        Document doc = builder.parse(in);
        get.releaseConnection();

        Element e = (Element) doc.getElementsByTagName("rdf:RDF").item(0);
        log.debug("got root " + e);
        NodeList n = e.getElementsByTagName("item");
        log.debug("found items " + n.getLength());
        for (int i = 0; i < n.getLength(); i++) {
            Bookmark bookmark = new Bookmark();
            Element l = (Element) n.item(i);
            bookmark.setName(((Element) l.getElementsByTagName("title").item(0)).getTextContent());
            bookmark.setUrl(((Element) l.getElementsByTagName("link").item(0)).getTextContent());
            if (l.getElementsByTagName("description").getLength() > 0) {
                bookmark.setNote(((Element) l.getElementsByTagName("description").item(0)).getTextContent());
            }
            children.add(bookmark);
            log.debug("added bookmark " + bookmark.getName() + " " + bookmark.getUrl());
        }

    } catch (HttpException e) {
        log.error("Error parsing delicious", e);
    } catch (IOException e) {
        log.error("Error parsing delicious", e);
    } catch (ParserConfigurationException e) {
        log.error("Error parsing delicious", e);
    } catch (SAXException e) {
        log.error("Error parsing delicious", e);
    } finally {
        if (get != null)
            get.releaseConnection();
    }

    log.debug("children: " + children.size());
    return children;
}

From source file:gsn.wrappers.HttpGetAndroidWrapper.java

private void parseXML() {
    URL url;/*from  ww w . j  a  v  a  2  s  . c o m*/

    try {
        url = new URL(urlPath);
        URLConnection conn = url.openConnection();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(conn.getInputStream());

        NodeList nodes = doc.getElementsByTagName("stream-element");

        for (int i = 0; i < nodes.getLength(); i++) {
            Element element = (Element) nodes.item(i);

            NodeList Long = element.getElementsByTagName("long");
            Element line = (Element) Long.item(0);
            Longitude = getCharacterDataFromElement(line);

            NodeList Lat = element.getElementsByTagName("lat");
            line = (Element) Lat.item(0);
            Latitude = getCharacterDataFromElement(line);
        }

        StreamElement streamElement = new StreamElement(FIELD_NAMES,
                new Byte[] { DataTypes.DOUBLE, DataTypes.DOUBLE },
                new Serializable[] { Double.parseDouble(Longitude), Double.parseDouble(Latitude) },
                System.currentTimeMillis());
        postStreamElement(streamElement);

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:WebCategorizer.java

public void getWebCategories(HashSet<String> urlSet, HashMap<String, String> websiteCategoryMap,
        MongoCollection<org.bson.Document> websiteCategoryCollection) {
    try {// ww w  .  j a  va  2 s.  com
        File file = new File(categoriesFile);
        JSONObject webCatList = new JSONObject();
        if (file.exists() && file.length() != 0) {
            webCatList = loadCategories();
        } else {
            webCatList = fetchCategories();
        }
        for (String url : urlSet) {
            if (websiteCategoryMap.containsKey(url))
                continue;
            org.bson.Document urlDoc = websiteCategoryCollection.find(eq("URLDomain", url)).first();
            if (urlDoc == null) {
                String host = "";
                String port = "";
                if (url.indexOf(':') > -1) {
                    String[] urlAddr = url.split(":");
                    host = urlAddr[0];
                    port = urlAddr[1];
                } else {
                    host = url;
                    port = "80";
                }
                StringBuilder remoteUrl = new StringBuilder("http://sp.cwfservice.net/1/R/");
                remoteUrl.append(k9License);
                remoteUrl.append("/K9-00006/0/GET/HTTP/");
                remoteUrl.append(host);
                remoteUrl.append("/");
                remoteUrl.append(port);
                remoteUrl.append("///");

                //Fetch Key for URL
                URL obj = new URL(remoteUrl.toString());
                URLConnection connection = obj.openConnection();

                Document doc = parseXML(connection.getInputStream());

                NodeList descNodes = doc.getElementsByTagName("DomC");
                if (descNodes.getLength() != 0) {
                    String cat = (String) webCatList
                            .get(breakString(descNodes.item(0).getTextContent().toLowerCase()));
                    websiteCategoryMap.put(url, cat);
                    websiteCategoryCollection.insertOne(new org.bson.Document("URLId", url.hashCode())
                            .append("URLDomain", url.toString()).append("URLCategory", cat));
                } else {
                    descNodes = doc.getElementsByTagName("DirC");
                    String cat = (String) webCatList
                            .get(breakString(descNodes.item(0).getTextContent().toLowerCase()));
                    websiteCategoryMap.put(url, cat);
                    websiteCategoryCollection.insertOne(new org.bson.Document("URLId", url.hashCode())
                            .append("URLDomain", url.toString()).append("URLCategory", cat));
                }
            } else {
                websiteCategoryMap.put(url, new JSONObject(urlDoc.toJson()).get("URLCategory").toString());
            }
        }
    } catch (Exception ex) {
        System.out.println(ex.getClass().getName());
        System.out.println("Not working");
    }
}

From source file:com.norconex.importer.parser.impl.xfdl.XFDLParser.java

private void parseXML(Document doc, Writer out, ImporterMetadata metadata) throws IOException {

    // Grab the title
    NodeList xmlTitles = doc.getElementsByTagName("title");
    if (xmlTitles != null && xmlTitles.getLength() > 0) {
        Node titleItem = xmlTitles.item(0);
        if (titleItem instanceof Element) {
            metadata.addString("title", ((Element) titleItem).getTextContent());
        }//from w w w  .j  av  a 2  s.c  o  m
    }

    boolean isEmpty = true;
    NodeList xmlFields = doc.getElementsByTagName("field");
    for (int i = 0; i < xmlFields.getLength(); i++) {
        if (xmlFields.item(i) instanceof Element) {
            NodeList children = xmlFields.item(i).getChildNodes();
            for (int j = 0; j < children.getLength(); j++) {
                Node childItem = children.item(j);
                if (childItem instanceof Element) {
                    Element tag = ((Element) childItem);
                    String tagName = tag.getTagName();
                    if ("value".equalsIgnoreCase(tagName)) {
                        isEmpty = writeValue(out, tag.getTextContent(), isEmpty);
                    }
                }
            }
        }
    }
}

From source file:fr.redteam.dressyourself.plugins.weather.yahooWeather.YahooWeatherUtils.java

private void parseForecastInfo(final ForecastInfo forecastInfo, final Document doc, final int pIndex) {
    Node forecast1ConditionNode = doc.getElementsByTagName("yweather:forecast").item(pIndex);
    forecastInfo.setForecastCode(// www .j  a v  a 2 s .c  o m
            Integer.parseInt(forecast1ConditionNode.getAttributes().getNamedItem("code").getNodeValue()));
    forecastInfo.setForecastText(forecast1ConditionNode.getAttributes().getNamedItem("text").getNodeValue());
    forecastInfo.setForecastDate(forecast1ConditionNode.getAttributes().getNamedItem("date").getNodeValue());
    forecastInfo.setForecastDay(forecast1ConditionNode.getAttributes().getNamedItem("day").getNodeValue());
    forecastInfo.setForecastTempHighF(
            Integer.parseInt(forecast1ConditionNode.getAttributes().getNamedItem("high").getNodeValue()));
    forecastInfo.setForecastTempLowF(
            Integer.parseInt(forecast1ConditionNode.getAttributes().getNamedItem("low").getNodeValue()));
}

From source file:org.ambraproject.article.service.ArticleDocumentServiceTest.java

@Test
public void testGetFullXml() throws Exception {
    Article article = new Article("info:doi/10.1371/journal.pgen.1000096");
    dummyDataStore.store(article);// w w w. j  a v  a  2 s . c o m

    Document xml = articleDocumentService.getFullDocument(article.getDoi());
    assertNotNull(xml, "returned null xml document");

    //check the doi from the xml
    NodeList articleIdNodes = xml.getElementsByTagName("article-id");
    for (int i = 0; i < articleIdNodes.getLength(); i++) {
        Node node = articleIdNodes.item(i);
        if (node.getAttributes().getNamedItem("pub-id-type").getNodeValue().equals("doi")) {
            assertEquals(node.getChildNodes().item(0).getNodeValue(),
                    article.getDoi().replaceFirst("info:doi/", ""), "returned article xml with incorrect doi");
            break;
        }
    }
}

From source file:prodoc.FTRemote.java

/**
 * Communicates to the OpenProdoc Server by http sending instructionss
 * @param pOrder Order to execute//  w w  w  .ja v a  2  s  .c  o m
 * @param pParam Parameters of the order (can be empty or null depending on order
 * @return an xml node extracted form XML answer.
 * @throws PDException in any error
 */
private Node ReadWrite(String pOrder, String pParam) throws PDException {
    Node OPDObject = null;
    CloseableHttpResponse response2 = null;
    if (PDLog.isDebug()) {
        PDLog.Debug("DriverRemote. ReadWrite: Order:" + pOrder);
        PDLog.Debug("Param:" + pParam);
    }
    try {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(ORDER, pOrder));
        nvps.add(new BasicNameValuePair(PARAM, pParam));
        UrlPost.setEntity(new UrlEncodedFormEntity(nvps));
        response2 = httpclient.execute(UrlPost, context);
        HttpEntity Resp = response2.getEntity();
        Document XMLObjects = DB.parse(Resp.getContent());
        NodeList OPDObjectList = XMLObjects.getElementsByTagName("Result");
        OPDObject = OPDObjectList.item(0);
        if (OPDObject.getTextContent().equalsIgnoreCase("KO")) {
            OPDObjectList = XMLObjects.getElementsByTagName("Msg");
            if (OPDObjectList.getLength() > 0) {
                OPDObject = OPDObjectList.item(0);
                PDException.GenPDException("Server_Error", DriverGeneric.DeCodif(OPDObject.getTextContent()));
            } else
                PDException.GenPDException("Server_Error", "");
        }
        OPDObjectList = XMLObjects.getElementsByTagName("Data");
        OPDObject = OPDObjectList.item(0);
    } catch (Exception ex) {
        if (PDLog.isDebug())
            ex.printStackTrace();
        PDException.GenPDException(ex.getLocalizedMessage(), "");
    } finally {
        if (response2 != null)
            try {
                response2.close();
            } catch (IOException ex) {
                PDException.GenPDException(ex.getLocalizedMessage(), "");
            }
    }
    return (OPDObject);
}

From source file:com.sinnerschrader.s2b.accounttool.logic.component.licences.LicenseSummary.java

private List<Dependency> loadFromXML(Resource licenseFile) throws Exception {
    List<Dependency> deps = new LinkedList<>();
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(licenseFile.getInputStream());

    NodeList dependencyNodes = doc.getElementsByTagName("dependency");
    for (int di = 0; di < dependencyNodes.getLength(); di++) {
        Node nNode = dependencyNodes.item(di);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
            Element dependency = (Element) nNode;
            String groupId = getElementsByTagName(dependency, "groupId");
            String artifactId = getElementsByTagName(dependency, "artifactId");
            String version = getElementsByTagName(dependency, "version");
            List<License> licenses = new ArrayList<>();

            log.trace("Found dependency {}:{}:{} ", groupId, artifactId, version);

            NodeList licenseNodes = dependency.getElementsByTagName("license");
            for (int li = 0; li < licenseNodes.getLength(); li++) {
                Node lNode = licenseNodes.item(li);
                if (lNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element license = (Element) lNode;
                    String name = getElementsByTagName(license, "name");
                    String distribution = getElementsByTagName(license, "distribution");
                    String url = getElementsByTagName(license, "url");
                    String comments = getElementsByTagName(license, "comments");

                    log.trace("Found license {} for dependency {}:{}:{} ", name, groupId, artifactId, version);
                    licenses.add(new License(name, url, distribution, comments));
                }/*  ww  w  .j  a  v a2  s  . c  o  m*/
            }
            deps.add(new Dependency(groupId, artifactId, version, licenses));
        }
    }
    Collections.sort(deps);
    return deps;
}

From source file:com.stratio.decision.service.SolrOperationsService.java

public void createSolrSchema(List<ColumnNameTypeValue> columns, String confpath)
        throws ParserConfigurationException, URISyntaxException, IOException, SAXException,
        TransformerException {/* ww w . j a va2s . co  m*/
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setIgnoringComments(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(new File(ClassLoader.getSystemResource("./solr-config/schema.xml").toURI()));
    NodeList nodes = doc.getElementsByTagName("schema");
    for (ColumnNameTypeValue column : columns) {
        Element field = doc.createElement("field");
        field.setAttribute("name", column.getColumn());
        field.setAttribute("type", streamingToSolr(column.getType()));
        field.setAttribute("indexed", "true");
        field.setAttribute("stored", "true");
        nodes.item(0).appendChild(field);
    }
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult streamResult = new StreamResult(new File(confpath + "/schema.xml"));
    transformer.transform(source, streamResult);
}