JAVA converts xml data into entity classes

Use JAXB (Java Architecture for XML Binding) to realize the conversion between XML and Bean

Introduction

JAXB is an industry standard and a technology that can generate Java classes based on XML Schema. During this process, JAXB also provides a method to reversely generate a Java object tree from the XML instance document, and can rewrite the contents of the Java object tree to the XML instance document.
Jaxb 2.0 is an integral part of JDK 1.6. We don’t need to download third-party jar packages to make easy conversion. Jaxb2 uses the new features of JDK, such as: Annotation, GenericType, etc., and annotation annotations need to be added to the JavaBean to be converted.

Common annotations

@XmlRootElement
Identifies that this class or enumeration type is the root element, mapped to an XML element. Annotations in JAXB act on classes.

@XmlElement
Map properties of java objects to nodes of xml. Map attributes without get methods/set methods to XML, acting on fields or methods.

@XmlAttribute
Maps properties of java objects to properties of nodes of xml.

@XmlAccessorType
Possible values:
FIELD: Non-static, non-transient fields in bound classes (everything, properties without getters/setters are fine) will be automatically bound mapped to XML, unless annotated by XmlTransient.

NONE: None of the fields or properties can be bound to XML unless they are specifically annotated with some JAXB annotations.

PROPERTY: (every, only properties with get/set methods) in the binding class are automatically bound to map to XML, unless annotated by XmlTransient.

PUBLIC_MEMBER: Every public getter/setter pair and every public field will automatically bind to XML unless annotated by XmlTransient.

@XmlTransient (non-transient)
It is used to indicate that this attribute is ignored when mapping XML from a Java object, and this element will not appear in the generated XML file.

Example

xml content

Entity Mapping



xml tool class

public class JAXBUtil {<!-- -->

    /**
     * Convert XML to POJO type
     */
    @SuppressWarnings("rawtypes")
    public static Object unmarshall(String xml, Class clsToUnbound) throws JAXBException, UnsupportedEncodingException {<!-- -->
        JAXBContext jc = JAXBContext. newInstance(clsToUnbound);

        return unmarshall(jc, xml);
    }

    private static Object unmarshall(JAXBContext jc, String xml) throws JAXBException, UnsupportedEncodingException {<!-- -->
        Unmarshaller u = jc. createUnmarshaller();
        InputStream is = new ByteArrayInputStream(xml. getBytes("UTF-8"));
        return u. unmarshal(is);
    }

    /**
     * Deserialize the object from the stream.
     *
     * @param cls The object type that needs to be deserialized.
     * @param xmlIs stream object
     * @return The deserialized object instance.
     * @throws JAXBException
     */
    public static Object unmarshall(InputStream xmlIs, Class<?> cls) throws JAXBException {<!-- -->
        JAXBContext jc = JAXBContext. newInstance(cls);
        Unmarshaller unmarshaller = jc. createUnmarshaller();
        Object obj = unmarshaller. unmarshal(xmlIs);
        return obj;
    }

    @SuppressWarnings("unchecked")
    public Object unmarshall(String xml, Class<? extends Object>... classes) throws JAXBException, IOException {<!-- -->
        InputStream is = new ByteArrayInputStream(xml. getBytes());
        JAXBContext jc = JAXBContext. newInstance(classes);
        Unmarshaller unmarshaller = jc. createUnmarshaller();
        unmarshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
        Object obj = unmarshaller. unmarshal(is);
        return obj;
    }

    /**
     * POJO type conversion to XML
     *
     * @param jc
     * @param serObj
     * @param formatOutput Whether to format
     * @param fragment whether to hide the header
     * @return
     * @throws JAXBException
     * @throws PropertyException
     */
    private static String marshall(JAXBContext jc, Object serObj, boolean formatOutput, boolean fragment) throws JAXBException, PropertyException {<!-- -->
        StringWriter out = new StringWriter();
        Marshaller m = jc. createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formatOutput);
        m.setProperty(Marshaller.JAXB_FRAGMENT, fragment);
        m.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
        m.marshal(serObj, out);
        String tmp = out. toString();
        return tmp;
    }

    @SuppressWarnings("rawtypes")
    public static String marshall(Object serObj, Class clsToBound) throws JAXBException {<!-- -->
        JAXBContext jc = JAXBContext. newInstance(clsToBound);
        return marshall(jc, serObj, true, false);
    }

    public static String marshall(Object serObj, boolean formatOutput, boolean fragment) throws JAXBException {<!-- -->
        JAXBContext jc = JAXBContext. newInstance(serObj. getClass());
        return marshall(jc, serObj, formatOutput, fragment);
    }

    public static String marshall(Object serObj, boolean formatOutput) throws JAXBException {<!-- -->
        return marshall(serObj, formatOutput, false);
    }

    /**
     * Serialize the class into the stream.
     *
     * @param contextPath needs to be serialized to the class name
     * @param obj the instance object that needs to be serialized
     * @param stream The stream object to be serialized to.
     * @throws JAXBException
     */
    public static void marshall(String contextPath, Object obj, OutputStream stream) throws JAXBException {<!-- -->
        JAXBContext jc = JAXBContext. newInstance(contextPath);
        Marshaller m = jc. createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        m.marshal(obj, stream);
    }
}

Test Code

Results

bean = Forecast_Content(PubListName=Forecast for the South China Sea, seaAreas=[SeaArea(items=[Item(NameCHS=Shizi Sea, NameEN=shizi sea, forecastContentList=[ForecastContent(time=20:00 on the 23rd, WaveHeightStr=0.1 -0.3)]), Item(NameCHS=Inner Lingding Sea, NameEN=lingding sea, forecastContentList=[ForecastContent(time=20:00 on the 23rd, WaveHeightStr=0.2-0.6)]), Item(NameCHS=Chinese white dolphin protection District, NameEN=, forecastContentList=[ForecastContent(time=20:00 on the 23rd, WaveHeightStr=0.3-0.7)]), Item(NameCHS=outer lingding sea, NameEN=outer lingding sea, forecastContentList=[ForecastContent(time=23 Sun 20:00, WaveHeightStr=0.5-0.8)]), Item(NameCHS=Guishan Island waters, NameEN=guishan, forecastContentList=[ForecastContent(time=23rd 20:00, WaveHeightStr=0.7-1.0)])])] )