Java XML Child Node Get getChildNodeValueByName(Node parent, String nodeName)

Here you can find the source of getChildNodeValueByName(Node parent, String nodeName)

Description

Gets a node value by name

License

Open Source License

Parameter

Parameter Description
parent the parent node
nodeName the node name

Exception

Parameter Description
Exception an exception

Return

String the value of the node

Declaration

public static String getChildNodeValueByName(Node parent, String nodeName) throws Exception 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2015 CA.  All rights reserved.
 *
 * This source file is licensed under the terms of the Eclipse Public License 1.0
 * For the full text of the EPL please see https://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/

import org.w3c.dom.Node;

public class Main {
    /**/*from w  w  w.j  a  v  a  2 s.  c  o  m*/
     * Gets a node value by name
     * 
     * @param parent   the parent node
     * @param nodeName   the node name
     * @return String   the value of the node 
     * @throws Exception
     */
    public static String getChildNodeValueByName(Node parent, String nodeName) throws Exception {
        Node node = findChildNodeByName(parent, nodeName);
        if (node != null && node.getFirstChild() != null) {
            return node.getFirstChild().getNodeValue().trim();
        }

        return "";
    }

    /**
     * Search a child node by name 
     * 
     * @param parent   the parent node
     * @param nodeName   the node name for searching
     * @return         Node with the specified name
     * @see            Node
     * @throws Exception
     */
    public static Node findChildNodeByName(Node parent, String nodeName) throws Exception {

        Node child = null;
        Node node = parent.getFirstChild();
        while (node != null) {
            if (node.getNodeName().equals(nodeName)) {
                child = node;
                break;
            }
            node = node.getNextSibling();
        }

        return child;
    }
}

Related

  1. getChildNodeValue(Element node, String tagName)
  2. getChildNodeValue(Element root, String childNodeName, String defaultValue)
  3. getChildNodeValue(Node node, String elementName)
  4. getChildNodeValue(Node root, String childName, boolean emptyStringOnMissingChild)
  5. getChildNodeValue(String childNodeName, Node n)
  6. getChildNodeWithName(Node node, String name, String namespaceURI)
  7. getChildNodeWithName(String name, Node n)
  8. getChildNodeWithTag(Node node, String nodeTag)