All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.bingoohuang.utils.xml.Xmls Maven / Gradle / Ivy

There is a newer version: 0.0.25
Show newest version
package com.github.bingoohuang.utils.xml;

import com.google.common.base.Throwables;
import com.google.common.collect.Sets;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import javax.xml.bind.JAXB;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.EnumSet;

public class Xmls {
    public enum MarshalOption {
        PrettyFormat, WithXmlDeclaration
    }

    public static String marshal(Object bean, MarshalOption... marshalOptions) {
        EnumSet enumSet = Sets.newEnumSet(Arrays.asList(marshalOptions), MarshalOption.class);
        return marshal(bean, enumSet, bean.getClass());
    }

    public static String marshal(Object bean, EnumSet marshalOptions, Class... types) {
        StringWriter sw = new StringWriter();

        try {
            JAXBContext carContext = JAXBContext.newInstance(types);
            Marshaller marshaller = carContext.createMarshaller();
            XMLOutputFactory xof = XMLOutputFactory.newInstance();
            XMLStreamWriter streamWriter = xof.createXMLStreamWriter(sw);
            PrettyPrintHandler handler = new PrettyPrintHandler(streamWriter, marshalOptions);
            XMLStreamWriter prettyPrintWriter = (XMLStreamWriter) Proxy.newProxyInstance(
                    XMLStreamWriter.class.getClassLoader(), new Class[]{XMLStreamWriter.class}, handler);
            marshaller.marshal(bean, prettyPrintWriter);
            String xml = sw.toString();
            xml = xml.replaceAll(" xmlns:xsi=\"http://www\\.w3\\.org/2001/XMLSchema-instance\" xsi:nil=\"true\"", "");
            return xml;
        } catch (Exception e) {
            throw Throwables.propagate(e);
        }
    }

    public static  T unmarshal(String xml, Class beanClass) {
        StringReader reader = new StringReader(xml);
        return JAXB.unmarshal(reader, beanClass);
    }

    public static String prettyXml(String xml) {
        final boolean omitXmlDeclaration = !xml.startsWith("




© 2015 - 2025 Weber Informatics LLC | Privacy Policy