Java XML Has Child getChildHash(Element elem, String elementName, String attrName)

Here you can find the source of getChildHash(Element elem, String elementName, String attrName)

Description

get Child Hash

License

Open Source License

Declaration

public static Hashtable<String, Element> getChildHash(Element elem, String elementName, String attrName) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.Hashtable;

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

public class Main {
    public static Hashtable<String, Element> getChildHash(Element elem, String elementName, String attrName) {
        if (elem == null)
            return null;
        NodeList nl = elem.getChildNodes();
        if (nl == null)
            return null;
        Hashtable<String, Element> retlist = new Hashtable<String, Element>(100);
        for (int n = 0; n < nl.getLength(); n++) {
            Node child = nl.item(n);
            if (child instanceof Element) {
                Element element = (Element) child;
                if (!elementName.equals(element.getTagName()))
                    continue;
                String keyValue = element.getAttribute(attrName);
                if (keyValue == null)
                    continue;
                retlist.put(keyValue, element);
            }//  w w w  .  j  a v a  2  s . c  om
        }
        if (retlist.size() == 0)
            return null;
        return retlist;
    }

    public static Hashtable<String, String> getChildHash(Element elem) {
        if (elem == null)
            return null;
        NodeList nl = elem.getChildNodes();
        if (nl == null)
            return null;
        Hashtable<String, String> retlist = new Hashtable<String, String>(nl.getLength());
        for (int n = 0; n < nl.getLength(); n++) {
            Node child = nl.item(n);
            if (child instanceof Element) {
                Element element = (Element) child;
                String key = element.getTagName();
                String value = getSimpleElementText(element);
                retlist.put(key, value);
            }
        }
        if (retlist.size() == 0)
            return null;
        return retlist;
    }

    public static String getSimpleElementText(Element node) {
        if (node == null)
            return null;
        StringBuffer sb = new StringBuffer();
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (child instanceof Text) {
                sb.append(child.getNodeValue());
            }
        }
        return sb.toString();
    }
}

Related

  1. getLastVisibleChildElement(Node parent, Hashtable hiddenNodes)
  2. hasActivityChildNode(Node node)
  3. hasAnyChildElement(final Element e)
  4. hasChild(Element element, String child)