Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.StringReader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.dom.DOMDocument;
import org.dom4j.dom.DOMDocumentFactory;
import org.dom4j.io.SAXReader;

public class Main {
    public static void main(String[] args) throws DocumentException {
        String newNode = "<node>value</node>";
        String text = "<root><given></given></root>";
        DOMDocumentFactory factory = new DOMDocumentFactory();
        SAXReader reader2 = new SAXReader();
        reader2.setDocumentFactory(factory);
        org.dom4j.Document document = reader2.read(new StringReader(text));
        Document newNodeDocument = reader2.read(new StringReader(newNode));

        Element givenNode = document.getRootElement().element("given");
        givenNode.add(newNodeDocument.getRootElement());

        org.dom4j.dom.DOMDocument w3cDoc = (DOMDocument) document;
        org.w3c.dom.Element e = w3cDoc.createElement("div");
        e.setAttribute("id", "someattr");

        w3cDoc.getDocumentElement().getFirstChild().insertBefore(e,
                w3cDoc.getDocumentElement().getElementsByTagName("node").item(0));
        System.out.println(document.asXML());
    }
}