Java XML Node Compare compare(Node n1, Node n2)

Here you can find the source of compare(Node n1, Node n2)

Description

Compares two DOM nodes for (deep) equality.

License

RPL License

Parameter

Parameter Description
n1 a parameter
n2 a parameter

Return

whether the nodes are equal

Declaration

public static final boolean compare(Node n1, Node n2) 

Method Source Code

//package com.java2s;
/*//from   www . jav  a 2 s .  c o m
 * Unless explicitly acquired and licensed from Licensor under another license, the contents of
 * this file are subject to the Reciprocal Public License ("RPL") Version 1.5, or subsequent
 * versions as allowed by the RPL, and You may not copy or use this file in either source code
 * or executable form, except in compliance with the terms and conditions of the RPL
 *
 * All software distributed under the RPL is provided strictly on an "AS IS" basis, WITHOUT
 * WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, AND LICENSOR HEREBY DISCLAIMS ALL SUCH
 * WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, QUIET ENJOYMENT, OR NON-INFRINGEMENT. See the RPL for specific language
 * governing rights and limitations under the RPL.
 *
 * http://opensource.org/licenses/RPL-1.5
 *
 * Copyright 2012-2015 Open Justice Broker Consortium
 */

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    /**
     * Compares two DOM nodes for (deep) equality.
     * @param n1
     * @param n2
     * @return whether the nodes are equal
     */
    public static final boolean compare(Node n1, Node n2) {
        boolean ret = true;
        ret &= n1.getLocalName().equals(n2.getLocalName());
        ret &= n1.getNamespaceURI().equals(n2.getNamespaceURI());
        String text = n1.getTextContent();
        if (text != null) {
            ret &= text.equals(n2.getTextContent());
        }
        NodeList children = n1.getChildNodes();
        ret &= (children.getLength() == n2.getChildNodes().getLength());
        for (int i = 0; ret && i < children.getLength(); i++) {
            final Node child = children.item(i);
            if (child instanceof Element) {
                ret &= compare(child, n2.getChildNodes().item(i));
            }
        }
        return ret;
    }
}

Related

  1. areEqual(Node left, Node right)
  2. compareLocations(Node node1, int offset1, Node node2, int offset2)
  3. compareNode(Node nQ, Node nN, Boolean considerLength, Map qvars)
  4. compareNodes(Node expected, Node actual)
  5. compareStringNode(Node node, String tag)