Java XML Node Value getNodeValue(Node node, String name, String defaultVal, int index)

Here you can find the source of getNodeValue(Node node, String name, String defaultVal, int index)

Description

Gets a value from a named child node

License

Open Source License

Parameter

Parameter Description
name The child node name
node The node

Return

The attribute value

Declaration

public static String getNodeValue(Node node, String name,
        String defaultVal, int index) 

Method Source Code

//package com.java2s;
/*/*www.  ja v  a2 s.  co  m*/
 *  Copyright (C) 2003 by Francois Guillet
 *  This program is free software; you can redistribute it and/or modify it under the
 *  terms of the GNU General Public License as published by the Free Software
 *  Foundation; either version 2 of the License, or (at your option) any later version.
 *  This program is distributed in the hope that it will be useful, but WITHOUT ANY
 *  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 *  PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 */

import org.w3c.dom.*;

public class Main {
    /**
     *  Gets a value from a named child node
     *
     *@param  name  The child node name
     *@param  node  The node
     *@return       The attribute value
     */
    public static String getNodeValue(Node node, String name,
            String defaultVal, int index) {
        NodeList nl = node.getChildNodes();
        if (nl.getLength() == 0)
            return defaultVal;

        Node n = getNodeFromNodeList(nl, name, index);
        if (n == null)
            return defaultVal;

        n = n.getChildNodes().item(0);
        if (n == null)
            return defaultVal;

        String value = n.getNodeValue();
        if (value == null)
            value = defaultVal;

        return value;
    }

    /**
     *  Gets a named node from a node list. Returns null if the node does not
     *  exist.
     *
     *@param  nl        The node list
     *@param  nodeName  The node name
     *@return           The node named nodeName
     */
    public static Node getNodeFromNodeList(NodeList nl, String nodeName,
            int index) {
        for (int i = 0; i < nl.getLength(); ++i) {
            Node n = nl.item(i);
            if (n.getNodeName().equals(nodeName)) {
                if (index-- == 0)
                    return n;
            }
        }
        return null;
    }
}

Related

  1. getNodeValue(Node node)
  2. getNodeValue(Node node)
  3. getNodeValue(Node node)
  4. getNodeValue(Node node)
  5. getNodeValue(Node node, String name, boolean trim)
  6. getNodeValue(Node node, String nodeKey)
  7. getNodeValue(Node nodeXML)
  8. getNodeValue(org.w3c.dom.Node node)
  9. getNodeValue(org.w3c.dom.Node node)