Java 怎么将字符串解析为新的XML元素

2019年8月11日20:47:22Java 怎么将字符串解析为新的XML元素已关闭评论 468 1294字阅读4分18秒

1.简介

Java 怎么将字符串解析为新的XML元素?——请看下文。

2.示例代码

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

 
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
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 org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main{
    public static void main(String[] argv) throws Exception{
        String element = "tah1986.com";
        System.out.println(fromString(element));
    }
    private static final DocumentBuilder docBuilder;
    private static final Transformer transformer;
    
    public static final Element fromString(final String element) {
        try {
            final Document doc = newDocument();
            transformer.transform(new StreamSource(
                    new StringReader(element)), new DOMResult(doc));
            return doc.getDocumentElement();
        } catch (final TransformerException e) {
            throw new InternalError("Transformer error");
        }
    }
    
    public static final Document newDocument() {
        return docBuilder.newDocument();
    }
}

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