Java XML JAXB String to Object xmlToJaxb(Class xmlClass, String xml)

Here you can find the source of xmlToJaxb(Class xmlClass, String xml)

Description

xml To Jaxb

License

Open Source License

Declaration

public static Object xmlToJaxb(Class<?> xmlClass, String xml) throws JAXBException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;

import javax.xml.bind.Unmarshaller;

public class Main {
    private final static int LOOKAHEAD = 1024;

    public static Object xmlToJaxb(Class<?> xmlClass, String xml) throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(xmlClass);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        JAXBElement<?> element;
        try (StringReader reader = new StringReader(xml)) {
            element = (JAXBElement<?>) unmarshaller.unmarshal(reader);
        }//from w w w.j  a va 2 s. com
        return element.getValue();
    }

    public static Object xmlToJaxb(Class<?> xmlClass, InputStream is) throws JAXBException, IOException {
        JAXBContext jaxbContext = JAXBContext.newInstance(xmlClass);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        JAXBElement<?> element = (JAXBElement<?>) unmarshaller.unmarshal(getReader(is));
        return element.getValue();
    }

    private static Reader getReader(InputStream is) throws IOException {
        Reader reader = new BufferedReader(new InputStreamReader(is));
        char c[] = "<?".toCharArray();
        int pos = 0;
        reader.mark(LOOKAHEAD);
        while (true) {
            int value = reader.read();

            // Check to see if we hit the end of the stream.
            if (value == -1) {
                throw new IOException("Encounter end of stream before start of XML.");
            } else if (value == c[pos]) {
                pos++;
            } else {
                if (pos > 0) {
                    pos = 0;
                }
                reader.mark(LOOKAHEAD);
            }

            if (pos == c.length) {
                // We found the character set we were looking for.
                reader.reset();
                break;
            }
        }

        return reader;
    }
}

Related

  1. xml2obj(final Class cls, final String xml)
  2. xml2Object(String content, Class valueType)
  3. Xml2Object(String xmlString, Class clazz)
  4. xmlToJavaBean(String xml, Class c)
  5. xmlToJaxb(Class xmlClass, String xml)
  6. xmlToObject(String xml, Class... type)
  7. xmlToObject(String xml, Class classe)
  8. XmlToObject(String xml, Class type)
  9. xmlToXhtml(T catalog, StreamSource xslt, StreamResult result)