2 qq 30866297 qq_30866297 于 2016.02.25 22:44 提问

XStream使用中,给xml加CDATA的代码运行后,没有加上CDATA字段

该问题是在学习柳峰的微信公众号平台开发中遇到的,希望能得到大神们的解答

希望得到大神们的解答

1个回答

qq_30866297
qq_30866297   2016.02.25 23:06

该问题是在学习柳峰的微信公众号平台开发基础课程第十节中遇到的,具体代码我附在后面,各位大神请看
package org.liufeng.test;

import java.io.Writer;

import org.liufeng.model.Person;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;

public class XStreamTest {
public static void main(String[] args) {
//创建一个Person对象
Person person = new Person();
person.setName("柳峰");
person.setInfo("我学习微信开发的老师");

    //设置别名
    xstream.alias("person",Person.class);
    String xml = xstream.toXML(person);
    System.out.println(xml);
}

//生成喊CDATA的xml
private static XStream xstream = new XStream(new XppDriver(){
    @SuppressWarnings("unused")
    public HierarchicalStreamWriter creatWriter(Writer out){
        return new PrettyPrintWriter(out){
            //对所有xml节点都增加CDATA标记
            boolean cdata = true;

            public void startNode(String name,@SuppressWarnings("rawtypes") Class clazz){
                super.startNode(name,clazz);
            }
            protected void writeText(QuickWriter writer,String text){
                if(cdata){
                    writer.write("<![CDATA[");
                    writer.write(text);
                    writer.write("]]>");
                }else{
                    writer.write(text);
                }
            }
        };
    }
});

}

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!