Java 怎么读取XML文件并进行转换

2019年7月30日22:58:51Java 怎么读取XML文件并进行转换已关闭评论 605 1546字阅读5分9秒

1.简介

Java 怎么读取XML文件并进行转换?——请看下文。

2.示例代码

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

 */


import java.io.StringWriter;

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 void main(String[] argv) throws Exception {
        String systemId = "tah1986.com";
        System.out.println(readFile(systemId));
    }

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

    
    public static String readFile(String systemId) throws Exception {
        
        StringWriter result = new StringWriter();
        transform(new StreamSource(systemId), new StreamResult(result),
                true);
        return checkResult(result, true);
    }

    
    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;
    }
}

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