Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.xml.sax.InputSource;

public class Main {
    /**
     * Create document from given string content.
     * @param data   content of xml document
     * @return
     * @throws IllegalArgumentException
     */
    public static Document createDocument(String data) throws IllegalArgumentException {
        return createDocument(data.toCharArray());
    }

    /**
     * Create document from given array.
     * @param data
     * @return
     * @throws IllegalArgumentException
     */
    public static Document createDocument(char[] data) throws IllegalArgumentException {
        Reader reader = new CharArrayReader(data);
        return createDocument(reader);
    }

    public static Document createDocument(Reader reader) throws IllegalArgumentException {
        // init DOM builder
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setCoalescing(true);
        factory.setIgnoringComments(true);
        factory.setIgnoringElementContentWhitespace(true);
        factory.setValidating(false);

        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource inputSource = new InputSource(reader);
            Document doc = builder.parse(inputSource);
            return doc;
        } catch (Exception ex) {
            IllegalArgumentException iae = new IllegalArgumentException(ex.getMessage());
            iae.initCause(ex);
            throw iae;
        }
    }
}