Get string value of XML element. - Java XML

Java examples for XML:XML Element Value

Description

Get string value of XML element.

Demo Code

/*******************************************************************************
     * Copyright (c) 2015-2016 Oak Ridge National Laboratory.
     * All rights reserved. This program and the accompanying materials
     * are made available under the terms of the Eclipse Public License v1.0
     * which accompanies this distribution, and is available at
     * http://www.eclipse.org/legal/epl-v10.html
     *******************************************************************************/
//package com.java2s;

import org.w3c.dom.Element;

import org.w3c.dom.Node;

public class Main {
    /** Get string value of an element.
     *  @param element Element/*from w  ww  .j  ava  2s.  com*/
     *  @return String of the node. Empty string if nothing found.
     */
    public static String getString(final Element element) {
        final Node text = element.getFirstChild();
        if (text == null) // <empty /> node
            return "";
        if ((text.getNodeType() == Node.TEXT_NODE || text.getNodeType() == Node.CDATA_SECTION_NODE))
            return text.getNodeValue();
        return "";
    }
}

Related Tutorials