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

com.crabshue.commons.xml.node.NodeConverter Maven / Gradle / Ivy

package com.crabshue.commons.xml.node;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
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 org.w3c.dom.Node;

import com.crabshue.commons.exceptions.SystemException;
import lombok.NonNull;

/**
 * Utility class to convert a {@link Node} to other formats.
 */
public class NodeConverter {

    /**
     * Convert a w3c dom node to a InputStream
     */
    public static InputStream toInputStream(@NonNull final Node node) {

        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        final Result outputTarget = new StreamResult(outputStream);

        try {
            final Transformer t = TransformerFactory.newInstance().newTransformer();
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            t.transform(new DOMSource(node), outputTarget);
        } catch (TransformerException e) {
            throw new SystemException(e);
        }

        return new ByteArrayInputStream(outputStream.toByteArray());
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy