Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2009, 2013 Andrew Gvozdev (Quoin Inc.).
 * 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:
 *     Andrew Gvozdev (Quoin Inc.)
 *******************************************************************************/

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import org.w3c.dom.Node;

public class Main {
    /**
     * The method creates an element with specified name and attributes and appends it to the parent element.
     * This is a convenience method for often used sequence of calls.
     *
     * @param parent - the node where to append the new element.
     * @param name - the name of the element type being created.
     * @param attributes - string array of pairs attributes and their values.
     *     Each attribute must have a value, so the array must have even number of elements.
     * @return the newly created element.
     *
     * @throws ArrayIndexOutOfBoundsException in case of odd number of elements of the attribute array
     *    (i.e. the last attribute is missing a value).
     */
    public static Element appendElement(Node parent, String name, String[] attributes) {
        Document doc = parent instanceof Document ? (Document) parent : parent.getOwnerDocument();
        Element element = doc.createElement(name);
        if (attributes != null) {
            int attrLen = attributes.length;
            for (int i = 0; i < attrLen; i += 2) {
                String attrName = attributes[i];
                String attrValue = attributes[i + 1];
                element.setAttribute(attrName, attrValue);
            }
        }
        parent.appendChild(element);
        return element;
    }

    /**
     * The method creates an element with specified name and appends it to the parent element.
     * This is a shortcut for {@link #appendElement(Node, String, String[])} with no attributes specified.
     *
     * @param parent - the node where to append the new element.
     * @param name - the name of the element type being created.
     * @return the newly created element.
     */
    public static Element appendElement(Node parent, String name) {
        return appendElement(parent, name, null);
    }
}