Java tutorial
//package com.java2s; //License from project: Open Source License import java.util.HashMap; import java.util.Map; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; public class Main { /** * Given a node, returns a map where, for each immediate child of this node * that is an element named A with a Text node with data B, there is an * entry in the map from A to B. If A contains no textual node, A maps to * <TT>null</TT>. If the element A appears more than once, the last * element encountered is respected. * * @param node * the node to get the map for * @return the map from children element names to their textual contents */ public static Map<String, String> elementsToText(Node node) { NodeList children = node.getChildNodes(); Map<String, String> e2t = new HashMap<String, String>(); for (int i = 0; i < children.getLength(); i++) { Node c = children.item(i); if (c.getNodeType() != Node.ELEMENT_NODE) continue; String elementName = ((Element) c).getTagName(); String text = containedText(c); e2t.put(elementName, text); } return e2t; } /** * Given an node, returns the child text node of this element. * * @param node * the node to get the text node from * @return the text node that is a child of this node, or <CODE>null</CODE> * if there is no such child */ public static String containedText(Node node) { NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node c = children.item(i); if (c.getNodeType() != Node.TEXT_NODE) continue; return ((Text) c).getData(); } return null; } }