Retrieve the attributes of XML Element object as a Map. - Java XML

Java examples for XML:XML Attribute

Description

Retrieve the attributes of XML Element object as a Map.

Demo Code


//package com.java2s;

import java.util.HashMap;

import java.util.Map;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class Main {
    /**//w ww  . j  a  v  a  2s  . c om
     * Retrieve the attributes of an Element object as a Map.
     * 
     * @param element
     *          The element to get the attributes of
     * 
     * @return
     *          A Map<String, String> of the attributes that were
     *          contained in the Element.  If there were no
     *          attributes and empty Map is returned.
     */
    public static Map<String, String> getAttributesMap(Node element) {

        Map<String, String> attributes = new HashMap<String, String>();

        NamedNodeMap attributeNNM = element.getAttributes();
        for (int i = 0; i < attributeNNM.getLength(); i++) {
            Node attribute = attributeNNM.item(i);
            attributes.put(attribute.getNodeName(),
                    attribute.getNodeValue());
        }

        return attributes;
    }
}

Related Tutorials