Java XML Child Element Text getChildText(Element parent, String kidName)

Here you can find the source of getChildText(Element parent, String kidName)

Description

Returns the string that is the content of a child from this node.

License

Open Source License

Parameter

Parameter Description
parent The parent.
kidName The name of the child node, which must be unique within the parent.

Declaration

public static String getChildText(Element parent, String kidName) 

Method Source Code


//package com.java2s;

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

public class Main {
    /**//from   ww  w.  java  2 s  .  c om
     * Returns the string that is the content of a child from this node. If
     * there is none, return {@code null}.
     *
     * @param parent  The parent.
     * @param kidName The name of the child node, which must be unique within
     *                the parent.
     */
    public static String getChildText(Element parent, String kidName) {
        Node elem = getUniqueChild(parent, kidName);
        if (elem == null)
            return null;
        elem.normalize();
        return elem.getTextContent();
    }

    /**
     * Returns the child of a parent with the given name. If there is none,
     * returns {@code null}. If there is more than one, throws {@link
     * IllegalArgumentException}.
     *
     * @param parent The parent.
     * @param name   The name of the child node.
     */
    public static Element getUniqueChild(Element parent, String name) {
        Element child = null;
        for (Node n = parent.getFirstChild(); n != null; n = n.getNextSibling()) {
            if (n.getNodeName().equals(name) && n instanceof Element) {
                if (child == null)
                    child = (Element) n;
                else
                    throw new IllegalArgumentException(
                            "more than one <" + name + "> tag inside <" + parent.getNodeName() + ">");
            }
        }
        return child;
    }
}

Related

  1. getChildText(Element parent, String childLocalName, String childNamespaceURI)
  2. getChildText(Element parent, String childName)
  3. getChildText(Element parent, String childName)
  4. getChildText(Element parent, String childName)
  5. getChildText(Element parent, String childName)
  6. getChildText(Element parent, String name)
  7. getChildText(Element root, String childName)
  8. getChildText(Element tag, String childTagName)
  9. getChildText(final Element element, final String tagName)