Java tutorial
//package com.java2s; import java.util.*; import org.w3c.dom.*; public class Main { public static void printElement(Element e) { List lst = getChildrenElement(e); if (lst.size() == 0) { System.out.print(e.getTagName() + "="); String value = getNodeText(e); if (value.trim().length() > 0) System.out.println(value); else System.out.println(); NamedNodeMap nn = e.getAttributes(); for (int i = 0; i < nn.getLength(); i++) { Attr attr = (Attr) e.getAttributes().item(i); System.out.println(attr.getName() + "=" + attr.getValue()); } } else { System.out.println(e.getTagName()); for (int i = 0; i < lst.size(); i++) { printElement((Element) lst.get(i)); } } } public static List getChildrenElement(Node n, String childTagName) { List lst = new ArrayList(); NodeList nl = n.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node cn = nl.item(i); if ((cn.getNodeType() == Node.ELEMENT_NODE) && (cn.getNodeName().equals(childTagName))) { lst.add(cn); } } return lst; } public static List getChildrenElement(Node n) { List lst = new ArrayList(); NodeList nl = n.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node cn = nl.item(i); if (cn.getNodeType() == Node.ELEMENT_NODE) { lst.add(cn); } } return lst; } /** * getNodeText * @param n node * @return text node content */ public static String getNodeText(Node n) { NodeList nl = n.getChildNodes(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < nl.getLength(); i++) { Node cn = nl.item(i); if (cn.getNodeType() == Node.TEXT_NODE) { Text txt = (Text) cn; sb.append(txt.getData().trim()); } } return sb.toString(); } }