Java XML JAXB Unmarshaller unmarshalInstance(final String data, final Class expectedType)

Here you can find the source of unmarshalInstance(final String data, final Class expectedType)

Description

unmarshal Instance

License

Apache License

Declaration

public static <T> T unmarshalInstance(final String data, final Class<T> expectedType) 

Method Source Code


//package com.java2s;
/*/*  ww  w  .j a v a 2s.  c  om*/
 * #%L
 * cobertura-metrics-model
 * %%
 * Copyright (C) 2013 Cobertura
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

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

import javax.xml.bind.Unmarshaller;

import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;

public class Main {
    public static <T> T unmarshalInstance(final String data, final Class<T> expectedType) {

        try {
            // Assume we should only unmarshal a single type.
            final JAXBContext ctx = JAXBContext.newInstance(expectedType);
            final Unmarshaller unmarshaller = ctx.createUnmarshaller();

            // To ignore the namespace and xml element localPart,
            // unmarshal the instance as a JAXBElement.
            final StreamSource streamSource = new StreamSource(new StringReader(data));
            final JAXBElement<T> jaxbElement = unmarshaller.unmarshal(streamSource, expectedType);

            // All done.
            return jaxbElement.getValue();

        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. unmarshalDOMElement(byte[] input)
  2. unmarshalFromReader(Reader reader, Class c)
  3. unmarshalFromString(Class clz, String input)
  4. unmarshalFromXml(Class clazz, String xml)
  5. unmarshalFromXml(final String xml, Class destinationClass)
  6. unmarshall(Class clazz, String string)
  7. unmarshall(Class c, Object o)
  8. unmarshall(Class cls, Element domRequest)
  9. unmarshall(InputStream is, Class clz)