Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.StringBufferInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

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

public class Main {

    private static final String studentData = "  <students>" + "    <student>" + "        <name>a</name>"
            + "    </student>" + "    <student>" + "        <name>b</name>" + "    </student>" + "    <student>"
            + "        <name>c</name>" + "    </student>" + "</students>";

    private static final String studentB = "    <student>" + "        <name>d</name>" + "    </student>";

    private static DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

    public static void main(String[] args) throws Exception {
        Document currentstudents = getCurrentstudents();
        Element student = getNewstudent();
        Element ndestudent = (Element) currentstudents.getElementsByTagName("students").item(0);
        Node firstDocImportedNode = currentstudents.importNode(student, true);
        ndestudent.appendChild(firstDocImportedNode);
    }

    private static Document getCurrentstudents() throws Exception {
        DocumentBuilder builder = dbFactory.newDocumentBuilder();
        Document docstudent = builder.parse(new StringBufferInputStream(studentData));
        return docstudent;
    }

    private static Element getNewstudent() throws Exception {
        DocumentBuilder builder = dbFactory.newDocumentBuilder();
        Document newstudent = builder.parse(new StringBufferInputStream(studentData));
        Element student = newstudent.getDocumentElement();
        return student;
    }
}