Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010 Robert "Unlogic" Olofsson (unlogic@unlogic.se).
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v3
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-3.0-standalone.html
 ******************************************************************************/

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

public class Main {
    /**
     * Adds or replaces node in parent.
     * @param parent
     * @param node
     * @throws Exception - Node cannot exist more than once,
     * i.e. multiple nodes with the same name cannot exist in parent.
     */
    public static void replaceSingleNode(Element parent, final Node node) throws RuntimeException {

        NodeList nodes = parent.getElementsByTagName(node.getNodeName());

        if (nodes.getLength() > 1) {
            throw new RuntimeException(
                    "Parent element contains multiple nodes with the name " + node.getNodeName());
        }
        if (nodes.getLength() == 0) {
            parent.appendChild(node);
        } else {
            parent.replaceChild(node, nodes.item(0));
        }
    }
}