Java 怎么执行XML标识转换

2019年7月31日23:31:16Java 怎么执行XML标识转换已关闭评论 478 1909字阅读6分21秒

1.简介

Java 怎么执行XML标识转换?——请看下文。

2.示例代码

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

 */

import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Main {


    
    public static final String DEFAULT_ENCODING = "UTF-8";
    
    public static final String DEFAULT_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";

    
    public static String identity(String xml) throws TransformerException {
        xml = removeBOM(xml);
        if (xml != null)
            xml = xml.trim();
        if ((xml == null) || (xml.length() == 0)) {
            throw new TransformerException("Empty XML.");
        }
        StringWriter result = new StringWriter();
        transform(new StreamSource(new StringReader(xml)),
                new StreamResult(result), false);
        return checkResult(result, false);
    }

    
    public static String removeBOM(String s) {
        if (s != null) {
            byte[] bom = new byte[3];
            bom[0] = (byte) 0xEF;
            bom[1] = (byte) 0xBB;
            bom[2] = (byte) 0xBF;
            try {
                String sbom = new String(bom, "UTF-8");
                s = s.trim();
                if (s.startsWith(sbom)) {
                    s = s.substring(1).trim();
                }
            } catch (UnsupportedEncodingException e) {
            }
        }
        return s;
    }

    
    public static void transform(javax.xml.transform.Source source,
            javax.xml.transform.Result result, boolean indent)
            throws TransformerException {
        Transformer transformer = TransformerFactory.newInstance()
                .newTransformer();
        transformer
                .setOutputProperty(OutputKeys.ENCODING, DEFAULT_ENCODING);
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        if (indent) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(
                    "{http:
        }
        transformer.transform(source, result);
    }

    
    public static String checkResult(StringWriter result,
            boolean checkIndent) {
        String s = result.toString();
        if (s != null) {
            s = s.trim();
            if (checkIndent) {
                if (s.startsWith(DEFAULT_HEADER + "<")) {
                    s = s.replace(DEFAULT_HEADER, DEFAULT_HEADER + "\r\n");
                }
            }
            if (s.length() == 0)
                s = null;
        }
        ;
        return s;
    }
}

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