Aggregates all attributes from the given element, formats then into the proper key="value" XML format and returns them as one String - Java java.lang

Java examples for java.lang:Math Algorithm

Description

Aggregates all attributes from the given element, formats then into the proper key="value" XML format and returns them as one String

Demo Code

/*******************************************************************************
 * Copyright (c) 2006, 2008 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:// w w w. j  a  va  2s.c o  m
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
//package com.java2s;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class Main {
    /**
     * Aggregates all attributes from the given element, formats then into the
     * proper key="value" XML format and returns them as one String
     * 
     * @param element
     * @return The formatted String or null if the element has no attributes
     */
    private static String parseElementAttributes(Element element) {
        // Verify we have attributes
        if (element.hasAttributes() == false) {
            return null;
        }
        // Create the buffer
        StringBuffer buffer = new StringBuffer();
        // Get the attributes
        NamedNodeMap attributeMap = element.getAttributes();
        // Accumulate all attributes
        for (int i = 0; i < attributeMap.getLength(); i++) {
            Node node = attributeMap.item(i);
            if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
                Attr attribute = (Attr) node;
                // Append space before attribute
                buffer.append(' ');
                // Append attribute name
                buffer.append(attribute.getName());
                // Append =
                buffer.append('=');
                // Append quote
                buffer.append('"');
                // Append attribute value
                buffer.append(attribute.getValue());
                // Append quote
                buffer.append('"');
            }
        }

        return buffer.toString();
    }
}

Related Tutorials