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:Main.java

/**
 * Get textvalue from element path or attribute
 * @param doc//from ww w.j a  v  a2  s.  c o  m
 * @param path   path ("/root/channel/name") or
 *             attribute ("/root/channel/@id")
 * @return
 */
public static String getText(Document doc, String[] path) {
    NodeList nodes = doc.getElementsByTagName(path[0]);
    Element element = (Element) nodes.item(0);
    return getText(element, path, 1);
}

From source file:org.aectann.postage.TrackingStatusRefreshTask.java

private static String getFirstVaueOrNull(Document document, String tag) {
    NodeList elements = document.getElementsByTagName(tag);
    String result = null;/*from w  ww  .j  a  v  a  2s .  co  m*/
    if (elements.getLength() > 0) {
        Node firstChild = elements.item(0).getFirstChild();
        String nodeValue;
        if (firstChild != null && (nodeValue = firstChild.getNodeValue()) != null && nodeValue.length() > 0) {
            result = nodeValue;
        }
    }
    return result;
}

From source file:Main.java

/**
 * Given an XML string, return the textContent of all of the tags that match tagName as a list.
 * @param xmlStr/* w w w  . j  a  v a 2 s  . c  o  m*/
 * @param tagName
 * @method getValuesForNode
 * @static
 */
public static List<String> getValuesForNode(String xmlStr, String tagName) {

    List<String> values = new ArrayList<String>();
    try {

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

        InputStream is = new ByteArrayInputStream(xmlStr.getBytes("UTF-8"));

        Document doc = docBuilder.parse(is);

        doc.getDocumentElement().normalize();

        NodeList nodes = doc.getElementsByTagName(tagName);
        int nodeCount = nodes.getLength();

        for (int i = 0; i < nodeCount; i++) {
            Node node = nodes.item(i);
            values.add(node.getTextContent());
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return values;

}

From source file:Main.java

public static Node findNodeByAttribute(Document document, String tagName, String attributeName,
        String attributeValue) {/*from w  w  w . j a v a 2 s .c o m*/
    Node foundNode = null;
    NodeList nodes = document.getElementsByTagName(tagName);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        for (int j = 0; j < node.getAttributes().getLength(); j++) {
            Node attribute = node.getAttributes().item(j);
            if (attribute.getNodeName().equals(attributeName)
                    && attribute.getNodeValue().equals(attributeValue)) {
                foundNode = node;
                break;
            }
        }
        if (foundNode != null)
            break;
    }
    return foundNode;
}

From source file:net.ftb.data.news.RSSReader.java

public static List<NewsArticle> readRSS() {
    try {/*from  ww  w.  j a  va2 s  . c  o m*/
        List<NewsArticle> news = Lists.newArrayList();

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        URL u = new URL(Locations.feedURL);
        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.connect();
        if (conn.getResponseCode() != 200) {
            Logger.logWarn("News download failed");
            AppUtils.debugConnection(conn);
            conn.disconnect();
            return null;
        }
        Document doc = builder.parse(conn.getInputStream());
        NodeList nodes = doc.getElementsByTagName("item");

        for (int i = 0; i < nodes.getLength(); i++) {
            Element element = (Element) nodes.item(i);
            NewsArticle article = new NewsArticle();
            article.setTitle(getTextValue(element, "title"));
            article.setHyperlink(getTextValue(element, "link"));
            article.setBody(getTextValue(element, "content:encoded"));
            article.setDate(getTextValue(element, "pubDate"));
            news.add(article);
        }

        return news;
    } catch (Exception ex) {
        Logger.logWarn("News download failed", ex);
        return null;
    }
}

From source file:Main.java

/**
 * DOM Parser method. /*from w w w.  ja v a2 s  .  c  om*/
 * Converts the input xmlString into List<String> of all the text in the nodes named nodeName.
 * The memory footprint is small enough when we deal with less than 200 tweets.
 * 
 * @param xmlString
 *            The xml string
 * @param nodeName
 *            the name of the node, we are intersted in (e.g. "text")
 * @param trimString
 *            if we want to trim a particular pattern from every node's text, we pass it as trimString, e.g. "(https?://[^\\s]+)"
 * @return List of all the text strings from every node named nodeName. trimString text is trimmed from the result strings.
 */
public static List<String> parseNodesFromXml(String xmlString, String nodeName, String trimString) {
    List<String> nodeTexts = new ArrayList<String>();

    try {
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource inputSource = new InputSource();
        inputSource.setCharacterStream(new StringReader(xmlString));

        try {
            Document document = db.parse(inputSource);
            NodeList nodes = document.getElementsByTagName(nodeName);
            for (int i = 0; i < nodes.getLength(); i++) {
                String nodeText = nodes.item(i).getTextContent();
                String trimmedNodeText = trimStringFromText(trimString, nodeText);
                nodeTexts.add(trimmedNodeText);
            }

        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }

    return nodeTexts;
}

From source file:Main.java

/**
 * Returns the element specified with the given tag name in the specified XML text. Assumes that
 * there is only one tag of the speicified name in the XML text.
 * // www . j a  va 2 s  . c  o  m
 * @param xmlText
 * @param tagName
 * @return
 */
public static Element getSingleElement(String xmlText, String tagName) {
    if (!hasSingleTag(xmlText, tagName)) {
        return null;
    }

    Document doc = getDomDocument(xmlText);
    NodeList nodes = doc.getElementsByTagName(tagName);
    return (Element) nodes.item(0);
}

From source file:Main.java

/**
 * Appends two documents/* ww  w.  j a  va  2  s.c  om*/
 * 
 * @param curDoc      source document
 * @param appendDoc      document to append to source
 * @param eleNameToAdd   element tag name in source to which the appendDoc has to be appended as a child
 * @throws Exception
 */
public static void appendDocs(Document curDoc, Document appendDoc, String eleNameToAdd) throws Exception {

    Node importNode = curDoc.importNode(appendDoc.getDocumentElement(), true);
    curDoc.getElementsByTagName(eleNameToAdd).item(0).appendChild(importNode);

}

From source file:com.amazon.advertising.api.sample.ItemLookupSample.java

private static NodeList fetchASIN(String response) {
    NodeList nodelist = null;/*from   w ww.  j  a  v  a 2 s. c o m*/
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(response);
        nodelist = doc.getElementsByTagName("ASIN");

    } catch (Exception e) {
        e.printStackTrace();
    }
    return nodelist;
}

From source file:Main.java

public static String getCharacterDataFromDocumentWithKey(final Document document, final String key) {
    String result = null;//w  w w  . j  av a  2  s . c  o  m
    if (document != null) {
        final NodeList jobNodeList = document.getElementsByTagName(key);
        final CharacterData characterData = (CharacterData) jobNodeList.item(0).getChildNodes().item(0);
        result = characterData.getNodeValue();

    }
    return result;
}