Java tutorial
//package com.java2s; /* * Copyright 2002-2012 George Norman * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.HashMap; import java.util.Map; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * For the given {@code sourceNode}, read each "top level" element into the resulting {@code Map}. Each element name * is a key to the map, each element value is the value paired to the key. Example - anchor is the node, label and * href are keys: * * <pre> * {@code * <anchor> * <label>Slashdot</label> * <href>http://slashdot.org/</href> * </anchor> * } * </pre> */ public static Map<String, String> readNodeElementsToMap(final Node sourceNode) { Map<String, String> result = new HashMap<String, String>(); if (sourceNode == null) { return result; } NodeList childNodes = sourceNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node element = childNodes.item(i); if (element.getNodeType() == Node.ELEMENT_NODE) { String elementName = element.getNodeName(); String elementValue = ""; Node firstChild = element.getFirstChild(); if (firstChild != null) { elementValue = firstChild.getNodeValue(); } if (elementValue != null) { result.put(elementName, elementValue); } } } return result; } }