Java XML Element to String extractTextElementValue(final Element textElement)

Here you can find the source of extractTextElementValue(final Element textElement)

Description

Trivial convenience method to extract the value of a (text) Element, coping with the possibility that text child Nodes may not have been coalesced.

License

Open Source License

Parameter

Parameter Description
textElement a parameter

Declaration

public static String extractTextElementValue(final Element textElement) 

Method Source Code

//package com.java2s;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    /**//from w ww .j ava  2  s . c o m
     * Trivial convenience method to extract the value of a (text) Element, coping with the
     * possibility that text child Nodes may not have been coalesced.
     * 
     * @param textElement
     */
    public static String extractTextElementValue(final Element textElement) {
        NodeList childNodes = textElement.getChildNodes();
        String result;
        if (childNodes.getLength() == 1) {
            /* Text Nodes have been coalesced */
            result = ensureExtractTextNodeValue(childNodes.item(0));
        } else {
            /* Need to coalesce manually */
            StringBuilder resultBuilder = new StringBuilder();
            for (int i = 0; i < childNodes.getLength(); i++) {
                resultBuilder.append(ensureExtractTextNodeValue(childNodes.item(i)));
            }
            result = resultBuilder.toString();
        }
        return result;
    }

    private static String ensureExtractTextNodeValue(final Node node) {
        if (node.getNodeType() == Node.TEXT_NODE) {
            return node.getNodeValue();
        }
        throw new IllegalArgumentException("Node is not a text Node");
    }
}

Related

  1. elementToString(Element element)
  2. elementToString(Element elt, String prefix)
  3. elementToString(final Element element)
  4. extractText(Element element)
  5. extractText(Element obj, String localName)
  6. getElementAsInputStream(Element xml)
  7. getElementText(Element e)
  8. getNamedElemXml(Element parent, String elementName)
  9. getString(Element el, String label)