Java XML Attribute Copy copyAttributes(Element from, Element to, NodeFilter filter)

Here you can find the source of copyAttributes(Element from, Element to, NodeFilter filter)

Description

copies all attributes from one Element to another

License

BSD License

Parameter

Parameter Description
from - the Element which the source attributes
to - the target Element for the Attributes
filter - a NodeFilter to apply during copy

Declaration

public static void copyAttributes(Element from, Element to, NodeFilter filter) 

Method Source Code


//package com.java2s;
/*//  w  w  w.  j a v  a2 s .c  om
 * Copyright (c) 2012. betterFORM Project - http://www.betterform.de
 * Licensed under the terms of BSD License
 */

import org.w3c.dom.*;
import org.w3c.dom.traversal.NodeFilter;

public class Main {
    /**
     * copies all attributes from one Element to another
     *
     * @param from   - the Element which the source attributes
     * @param to     - the target Element for the Attributes
     * @param filter - a NodeFilter to apply during copy
     */
    public static void copyAttributes(Element from, Element to, NodeFilter filter) {
        if ((from != null) && (to != null)) {
            NamedNodeMap map = from.getAttributes();

            /* if filter is null use our own default filter, which accepts
               everything (this saves us from always check if filter is
               null */
            if (filter == null) {
                filter = new NodeFilter() {
                    public short acceptNode(Node n) {
                        return NodeFilter.FILTER_ACCEPT;
                    }
                };
            }

            if (map != null) {
                int len = map.getLength();

                for (int i = 0; i < len; i++) {
                    Node attr = map.item(i);

                    if (attr.getNodeType() == Node.ATTRIBUTE_NODE) {
                        if (filter.acceptNode(attr) == NodeFilter.FILTER_ACCEPT) {
                            to.setAttributeNS(attr.getNamespaceURI(), attr.getNodeName(), attr.getNodeValue());
                        }
                    }
                }
            }
        }
    }
}

Related

  1. copyAttribute(Element source, String srcattr, Element dest, String destattr)
  2. copyAttribute(Element sourceElement, String sourceAttrName, Element visualElement, String visualAttrName)
  3. copyAttributeNodes(Element source, Element target)
  4. copyAttributes(Element elementFrom, Element elementTo)
  5. copyAttributes(Element from, Element to)
  6. copyAttributes(Element fromEl, Element toEl)
  7. copyAttributes(final Element destElement, final Element srcElement)
  8. copyAttributes(Node from, Node to)
  9. copyAttributes(Node sourceNode, Element visualElement)