Java 怎么将转义的XML转换为原始的“未转义”值(例如,将<hello>转换为)

2019年8月2日23:21:03Java 怎么将转义的XML转换为原始的“未转义”值(例如,将<hello>转换为)已关闭评论 1,448 968字阅读3分13秒

1.简介

Java 怎么将转义的XML转换为原始的“未转义”值(例如,将<;hello>;转换为)?——请看下文。

2.示例代码

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

import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Element;

public class Main{
    public static void main(String[] argv) throws Exception{
        String escaped = "tah1986.com";
        System.out.println(unescape(escaped));
    }
    
    public static String unescape(String escaped) throws XMLStreamException {
        if (escaped == null)
            return null;
        XMLStreamReader reader = XmlChunkerContext.inputFactory
                .createXMLStreamReader(new StringReader("<xml>" + escaped
                        + "</xml>"));
        StringWriter sw = new StringWriter(escaped.length());
        while (reader.hasNext()) {
            reader.next();
            if (reader.hasText())
                sw.append(reader.getText());
        }
        return sw.toString();
    }
}

 
继续阅读