Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

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

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

public class Main {
    private static final ThreadLocal<DocumentBuilderFactory> documentBuilderFactory = new ThreadLocal<DocumentBuilderFactory>() {
        protected DocumentBuilderFactory initialValue() {
            return DocumentBuilderFactory.newInstance();
        };
    };

    /**
     * Creates a document that has a deep copy of the element passed in as its document element
     * @param element
     * @return the new document
     */
    public static Document createDocumentFrom(Element element) {
        Document document = createEmptyDocument();
        Node clonedNode = element.cloneNode(true);
        clonedNode = document.adoptNode(clonedNode);
        document.appendChild(clonedNode);
        return document;
    }

    /**
     * Create an empty XML document for building up a DOM tree.
     * @return the document
     */
    public static Document createEmptyDocument() {
        try {
            DocumentBuilder documentBuilder = documentBuilderFactory.get().newDocumentBuilder();
            Document document = documentBuilder.newDocument();
            return document;
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        }
    }
}