com.crabshue.commons.xml.node.NodeConverter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of commons-xml Show documentation
Show all versions of commons-xml Show documentation
Library for XML documents operations.
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());
}
}