Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

import org.xml.sax.SAXException;

public class Main {

    public static Document stringToDocument(final String source) {
        String tmp = source.trim();
        if (!tmp.startsWith("<?xml")) {
            tmp = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + tmp;
        }
        String encode = "utf-8";
        Pattern p = Pattern.compile("<?.*encoding=\"([^ ]*)\".*?>");
        Matcher m = p.matcher(tmp);
        if (m.find()) {
            encode = m.group(1);
        }
        try {
            return DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(new ByteArrayInputStream(tmp.getBytes(encode)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        return null;
    }
}