Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

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

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

public class Main {
    /**
     * sets the value of an Element in the Xml Document.
     * finds the first occurance of the element and sets its value.
     * @param root the root Element.
     * @param elemName the name of the element to search for.
     * @return String the element value or null if not found.
     */
    public static void setNodeValue(Document doc, String elemName, String value) {
        Element root = doc.getDocumentElement();
        NodeList nl = root.getElementsByTagName(elemName);
        if (null != nl) {
            Node n = nl.item(0);
            if (null != n) {
                n.getFirstChild().setNodeValue(value);
            } else {
                addNode(doc, elemName, value);
            }
        } else {
            addNode(doc, elemName, value);
        }

    }

    /**
     * internal function for adding an element to the DOM tree.
     */
    private static void addNode(Document doc, String elemName, String value) {
        Element root = doc.getDocumentElement();
        Element elem = doc.createElement(elemName);
        elem.appendChild(doc.createTextNode(value));
        root.appendChild(elem);
    }
}