Java 怎么将DOM转换为字节(Byte)

2019年7月29日20:47:17Java 怎么将DOM转换为字节(Byte)已关闭评论 445 1922字阅读6分24秒

1.简介

Java 怎么将DOM转换为字节(Byte)?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Main{
    
    
    private static TransformerFactory transFact = TransformerFactory
            .newInstance();
    private static Map<String, Templates> templates = new HashMap<String, Templates>();
    public static byte[] transformDomToBytes(Document doc,
            String stylesheet, boolean withXmlDeclaration, Map parameters) {
        try {
            
            
            
            Transformer transformer = getTransformer(stylesheet);
            transformer.clearParameters();
            if (parameters != null) {
                for (Object o : parameters.keySet()) {
                    String k = (String) o;
                    transformer.setParameter(k, parameters.get(k));
                }
            }
            if (!withXmlDeclaration)
                transformer.setOutputProperty(
                        OutputKeys.OMIT_XML_DECLARATION, "yes");
            DOMSource source = new DOMSource(doc);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            StreamResult result = new StreamResult(output);
            transformer.transform(source, result);
            return output.toByteArray();
        } catch (TransformerConfigurationException tce) {
            Throwable x = tce;
            if (tce.getException() != null)
                x = tce.getException();
            throw new RuntimeException(x);
        } catch (TransformerException te) {
            Throwable x = te;
            if (te.getException() != null)
                x = te.getException();
            throw new RuntimeException(x);
        }
    }
    private static Transformer getTransformer(String xsltFile)
            throws TransformerConfigurationException {
        Templates tpl = (Templates) templates.get(xsltFile);
        if (tpl == null) {
            Source xsltSource = new StreamSource(xsltFile);
            tpl = transFact.newTemplates(xsltSource);
            if (tpl == null) {
                throw new RuntimeException("Stylesheet does not exist: "
                        + xsltFile);
            }
            templates.put(xsltFile, tpl);
        }
        return tpl.newTransformer();
    }
}

 
继续阅读
编程十万个怎么办