Example usage for org.w3c.dom Element getElementsByTagName

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

Introduction

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

Prototype

public NodeList getElementsByTagName(String name);

Source Link

Document

Returns a NodeList of all descendant Elements with a given tag name, in document order.

Usage

From source file:Main.java

public static void testx() {
    try {//from  w w  w.  j a v  a2 s  . c  om
        File fXmlFile = new File("C:\\Users\\is96092\\Desktop\\music\\Megaman2.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);

        //optional, but recommended
        //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        doc.getDocumentElement().normalize();

        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

        NodeList nList = doc.getElementsByTagName("staff");

        System.out.println("----------------------------");

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);

            System.out.println("\nCurrent Element :" + nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                System.out.println("Staff id : " + eElement.getAttribute("id"));
                System.out.println(
                        "First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
                System.out.println(
                        "Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
                System.out.println(
                        "Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
                System.out.println(
                        "Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());

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

From source file:com.omertron.traileraddictapi.tools.DOMHelper.java

/**
 * Gets the string value of the tag element name passed
 *
 * @param element/*from   w  w w  . ja  va  2 s .  c o  m*/
 * @param tagName
 * @return
 */
public static String getValueFromElement(Element element, String tagName) {
    NodeList elementNodeList = element.getElementsByTagName(tagName);

    String value = "";

    if (elementNodeList != null) {
        Element tagElement = (Element) elementNodeList.item(0);
        if (tagElement != null) {
            NodeList tagNodeList = tagElement.getChildNodes();
            if (tagNodeList != null && tagNodeList.getLength() > 0) {
                value = ((Node) tagNodeList.item(0)).getNodeValue();
            }
        }
    }

    return value;
}

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//from   w  w w. ja va 2  s .  c o  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:Main.java

public static void ReadXMLFile()

{

    try {/*  w ww .  j  av  a 2s.  co  m*/

        File fXmlFile = new File("D:\\FAR_Documents\\__Startamap\\Home.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);

        //optional, but recommended
        //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        doc.getDocumentElement().normalize();

        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

        NodeList nList = doc.getElementsByTagName("staff");

        System.out.println("----------------------------");

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);

            System.out.println("\nCurrent Element :" + nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                System.out.println("Staff id : " + eElement.getAttribute("id"));
                System.out.println(
                        "First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
                System.out.println(
                        "Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
                System.out.println(
                        "Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
                System.out.println(
                        "Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());

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

From source file:Main.java

/**
 * Get the list of all the elements of a parent element.
 * @param parentElement the parent element
 * @param elementName the name of the element
 * @return the list of the elements/*from www.j a  v a  2s.  c  om*/
 */
public static List<Element> getElementsByTagName(final Element parentElement, final String elementName) {

    if (elementName == null || parentElement == null) {
        return null;
    }

    final NodeList nStepsList = parentElement.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:fr.aliasource.webmail.server.proxy.client.http.DOMUtils.java

/**
 * Renvoie sous la forme d'un tableau la valeur des attributs donns pour
 * toutes les occurences d'un lment donne dans le dom
 * /*from   w ww.  ja  va2s.co m*/
 * <code>
 *  <toto>
 *   <titi id="a" val="ba"/>
 *   <titi id="b" val="bb"/>
 *  </toto>
 * </code>
 * 
 * et getAttributes(&lt;toto&gt;, "titi", { "id", "val" }) renvoie { { "a",
 * "ba" } { "b", "bb" } }
 * 
 * @param root
 * @param elementName
 * @param wantedAttributes
 * @return
 */
public static String[][] getAttributes(Element root, String elementName, String[] wantedAttributes) {
    NodeList list = root.getElementsByTagName(elementName);
    String[][] ret = new String[list.getLength()][wantedAttributes.length];
    for (int i = 0; i < list.getLength(); i++) {
        Element elem = (Element) list.item(i);
        for (int j = 0; j < wantedAttributes.length; j++) {
            ret[i][j] = elem.getAttribute(wantedAttributes[j]);
        }
    }
    return ret;
}

From source file:com.microsoft.tfs.core.clients.build.internal.utils.XamlHelper.java

public static String updateProperties(final String originalXaml, final Properties properties) {
    final ArrayList keys = new ArrayList(properties.keySet());

    final Document document = DOMCreateUtils.parseString(originalXaml);
    final Element root = document.getDocumentElement();

    // first update any properties that we already have
    final NodeList nodes = root.getElementsByTagName("x:String"); //$NON-NLS-1$
    for (int i = 0; i < nodes.getLength(); i++) {
        final Element element = (Element) nodes.item(i);
        final String key = element.getAttribute("x:Key"); //$NON-NLS-1$
        element.getFirstChild().getNodeValue();

        if (properties.containsKey(key)) {
            keys.remove(key);//from w  ww.j a  va 2 s.com
            element.getFirstChild().setNodeValue(properties.getProperty(key));
        }
    }

    // now add any new properties to the xaml
    for (final Iterator it = keys.iterator(); it.hasNext();) {
        final String key = (String) it.next();
        final Element element = DOMUtils.appendChild(root, "x:String"); //$NON-NLS-1$
        element.setAttributeNS(XAML_NAMESPACE, "x:Key", key); //$NON-NLS-1$
        element.setAttributeNS(XML_NAMESPACE, "xml:space", "preserve"); //$NON-NLS-1$ //$NON-NLS-2$
        DOMUtils.appendText(element, properties.getProperty(key));
    }

    return DOMSerializeUtils.toString(root, DOMSerializeUtils.INDENT).trim();
}

From source file:Main.java

public static Element findNode(Element parentNode, String nodeName) {
    if (parentNode == null)
        throw new NullPointerException("Parent Node cannot be null!");
    if (nodeName == null)
        throw new NullPointerException("Nodename cannot be null!");
    NodeList nodes = parentNode.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:fr.ece.epp.tools.Utils.java

public static void updateProduct(String path, String[] feature, boolean outOrno) {
    Document document = null;//from w w  w.  j a v a  2  s  . c om
    try {
        document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(path);
        Element root = document.getDocumentElement();
        Node features = root.getElementsByTagName("features").item(0);
        Element basefeature = document.createElement("feature");
        basefeature.setAttribute("id", "org.eclipse.platform");
        features.appendChild(basefeature);
        for (int i = 0; i < feature.length; i++) {
            if (feature[i] != null && feature[i].trim().length() > 0) {
                Element fea = document.createElement("feature");
                if (feature[i].endsWith(".feature.group")) {
                    int count = feature[i].length() - ".featyre.group".length();
                    String id = feature[i].substring(0, count);
                    fea.setAttribute("id", id);
                } else {
                    fea.setAttribute("id", feature[i]);
                }
                features.appendChild(fea);
            }
        }
        output(root, path);
        if (outOrno) {
            output(root, null);
        }

    } catch (SAXException e) {
    } catch (IOException e) {
    } catch (ParserConfigurationException e) {
    }
}

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/*from   www  .  ja  va  2 s . co m*/
            .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();

            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;

}