Java XML Element Get Value getValue(Element e, String tagName)

Here you can find the source of getValue(Element e, String tagName)

Description

Given a person element, must get the element specified by the tagName, then must traverse that Node to get the value.

License

Open Source License

Parameter

Parameter Description
e an Element
tagName a tag name

Return

s the value of a Node

Declaration

public static String getValue(Element e, String tagName) 

Method Source Code

//package com.java2s;
/********************************************************************
 * Copyright (c) 1999 The Bean Factory, LLC.
 * All Rights Reserved.// ww  w .  j ava  2 s .  c  o m
 *
 * The Bean Factory, LLC. makes no representations or
 * warranties about the suitability of the software, either express
 * or implied, including but not limited to the implied warranties of
 * merchantableness, fitness for a particular purpose, or
 * non-infringement. The Bean Factory, LLC. shall not be
 * liable for any damages suffered by licensee as a result of using,
 * modifying or distributing this software or its derivatives.
 *
 *******************************************************************/

import org.w3c.dom.*;

public class Main {
    /**
      Given a person element, must get the element specified
      by the tagName, then must traverse that Node to get the
      value.
      Step1) get Element of name tagName from e
      Step2) cast element to Node and then traverse it for its
       non-whitespace, cr/lf value.
      Step3) return it!
        
      NOTE: Element is a subclass of Node
        
      @param    e   an Element
      @param    tagName a tag name
      @return   s   the value of a Node
    */
    public static String getValue(Element e, String tagName) {
        try {
            //get node lists of a tag name from a Element
            NodeList elements = e.getElementsByTagName(tagName);

            Node node = elements.item(0);
            NodeList nodes = node.getChildNodes();

            //find a value whose value is non-whitespace
            String s;
            for (int i = 0; i < nodes.getLength(); i++) {
                s = ((Node) nodes.item(i)).getNodeValue().trim();
                if (s.equals("") || s.equals("\r")) {
                    continue;
                } else
                    return s;
            }

        } catch (Exception ex) {
            System.out.println(ex);
            ex.printStackTrace();
        }

        return null;

    }
}

Related

  1. getTrimmedTextContent(Element element)
  2. getTrimmedTextValue(Element valueEle)
  3. getType(Element elementType)
  4. getUniqueElement(Element root, String elementName)
  5. getUniqueSubnode(Element rootNode, String name)
  6. getValue(Element el)
  7. getValue(Element element)
  8. getValue(Element element)
  9. getValue(Element element)