Java XML Element Get Value getTextValue(Element ele, String tagName)

Here you can find the source of getTextValue(Element ele, String tagName)

Description

Returns the value of given tagName under given element.

License

Open Source License

Parameter

Parameter Description
ele xml element under which the tagName should be found
tagName tag name of the tag which value is read

Return

the value of given tagName under given element.

Declaration

public static String getTextValue(Element ele, String tagName) 

Method Source Code


//package com.java2s;
/*//from  w  w  w .j  a v  a  2  s .c  o m
* Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies). 
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/

import org.w3c.dom.*;

public class Main {
    /**
     * Returns the value of given tagName under given element.
     * 
     * E.g.
     * <ele>
     *    <tagName>MyValue</tagName>
     * </ele>
     * 
     * MyValue is returned in the above case.
     * 
     * @param ele xml element under which the tagName should be found
     * @param tagName tag name of the tag which value is read
     * @return the value of given tagName under given element.
     */
    public static String getTextValue(Element ele, String tagName) {
        String textVal = null;

        try {
            NodeList nl = ele.getElementsByTagName(tagName);
            if (nl != null && nl.getLength() > 0) {
                Element el = (Element) nl.item(0);
                Node firstChild = el.getFirstChild();
                if (firstChild != null)
                    textVal = firstChild.getNodeValue();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return textVal;
    }

    /**
     * Returns the value of given node
     * @param node node which value is to be returned
     * @return the value of given node
     */
    public static String getNodeValue(Node node) {
        String retval = "";
        try {
            Node firstChild = node.getFirstChild();
            if (firstChild != null)
                retval = firstChild.getNodeValue();
        } catch (Exception e) {
            return "";
        }
        return retval;
    }
}

Related

  1. getTexts(Element root, String elementName)
  2. getTextString(Element e)
  3. getTextTrim(Element element)
  4. getTextTrim(Element element)
  5. getTextValue(Element el, String tagName)
  6. getTextValue(Element ele, String tagName)
  7. getTextValue(Element ele, String tagName)
  8. getTextValue(Element ele, String tagName)
  9. getTextValue(Element ele, String tagName)