Java 怎么将DOM转换为UTF-8字符串的字节

2019年7月29日20:48:49Java 怎么将DOM转换为UTF-8字符串的字节已关闭评论 554 1361字阅读4分32秒

1.简介

Java 怎么将DOM转换为UTF-8字符串的字节?——请看下文。

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 Logger log = Logger.getLogger(DomUtil.class);
    
    
    private static TransformerFactory transFact = TransformerFactory
            .newInstance();
    
    public static byte[] domToBytes(Node doc, boolean withXmlDeclaration) {
        try {
            
            Transformer transformer = transFact.newTransformer();
            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();
            x.printStackTrace();
            log.error(x);
        } catch (TransformerException te) {
            
            Throwable x = te;
            if (te.getException() != null)
                x = te.getException();
            x.printStackTrace();
            log.error(x);
        }
        return null;
    }
}

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