Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.FileNotFoundException;

import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.SAXSource;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

public class Main {
    @SuppressWarnings("unchecked")
    public static <T> T readXMLFromString(Class<?> class1, String content)
            throws JAXBException, FileNotFoundException, SAXException, ParserConfigurationException {
        JAXBContext context = JAXBContext.newInstance(class1);
        Unmarshaller um = context.createUnmarshaller();

        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        spf.setFeature("http://xml.org/sax/features/validation", false);

        XMLReader xr = (XMLReader) spf.newSAXParser().getXMLReader();
        try (StringReader reader = new StringReader(content)) {
            SAXSource source = new SAXSource(xr, new InputSource(reader));

            T obj = (T) um.unmarshal(source);
            return obj;
        }
    }
}