// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
package december;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

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

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class XmlAndEncoding {
    public static void test(String label, String actual) throws UnsupportedEncodingException, ParserConfigurationException, SAXException {
        System.out.printf("%s labeled as %s: ",  actual, label);
        String xmls = "<?xml version='1.0' encoding='" + label + "' standalone='yes'?>\r\n<data>Blåbærgrød</data>";
        byte[] xmlb = xmls.getBytes(actual);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        try {
            @SuppressWarnings("unused")
            Document doc = db.parse(new ByteArrayInputStream(xmlb));
            System.out.println("OK");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
    public static void main(String[] args) throws Exception {
        test("UTF-8", "UTF-8");
        test("ISO-8859-1", "ISO-8859-1");
        test("ISO-8859-1", "UTF-8");
        test("UTF-8", "ISO-8859-1");
    }
}
