Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.StringReader;

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.xml.sax.InputSource;

public class Main {
    private final static DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

    /**
     * Convert and xml String to an org.w3c.dom.Element
     * @param xml - the XML
     * @return - the Element
     */
    public static Element stringToElement(String xml) {
        Element element = null;
        try {
            Document document = getDocumentBuilder().parse(new InputSource(new StringReader(xml)));
            element = (Element) document.getDocumentElement().cloneNode(true);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return element;
    }

    private static synchronized DocumentBuilder getDocumentBuilder() {
        try {
            return documentBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new RuntimeException("failed to create a new DocumentBuilder", e);
        }
    }
}