Java XML Attribute Remove removeEmptyAttributes(Element element)

Here you can find the source of removeEmptyAttributes(Element element)

Description

Remove all attributes having an empty value.

License

Open Source License

Parameter

Parameter Description
element The element to be processed.

Declaration

public static void removeEmptyAttributes(Element element) 

Method Source Code

//package com.java2s;
// License as published by the Free Software Foundation; either

import org.w3c.dom.Attr;

import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;

public class Main {
    /**//  w  w w.  j ava 2  s .  com
     * Remove all attributes having an empty value.
     * @param element The element to be processed.
     */
    public static void removeEmptyAttributes(Element element) {
        NamedNodeMap attributes = element.getAttributes();
        int attribCount = attributes.getLength();

        for (int i = attribCount - 1; i >= 0; i--) {
            Attr attribute = (Attr) attributes.item(i);

            // Note - doesn't account for namespaces.  Not needed here !
            if (attribute.getValue().equals("")) {
                attributes.removeNamedItem(attribute.getName());
            }
        }
    }

    /**
     * Get the name from the supplied element.
     * <p/>
     * Returns the {@link Node#getLocalName() localName} of the element
     * if set (namespaced element), otherwise the
     * element's {@link Element#getTagName() tagName} is returned.
     * <p/>
     * <b>NOTE</b>: Taken from Milyn Smooks.
     *
     * @param element The element.
     * @return The element name.
     */
    public static String getName(Element element) {

        String name = element.getLocalName();

        if (name != null) {
            return name;
        } else {
            return element.getTagName();
        }
    }
}

Related

  1. removeAttributes(Element elem)
  2. removeAttributes(Element element)
  3. removeAttributes(Element target, boolean flag)
  4. removeAttributes(SOAPElement elem)
  5. removeDefaultNameSpaceAttributes(final Element element)
  6. removeInvalidAttributes(Element element, String... validAttributeNames)
  7. removeNodeAttribute(Node node, String attributeName)
  8. removeNodeAttribute(Node node, String name)
  9. removeNodeAttributes(Node node)