Add CDATA using XStream for specific fields



I am new to xStream and I have following code to transfer my custom object into String in xml format.



public static String textMessageToXml(ResponseTextMessage textMsg){
xstream.alias("xml", textMsg.getClass());
return xstream.toXML(textMsg);
}

private static XStream xstream = new XStream(new XppDriver() {
@Override
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// Add CDATA block
boolean cdata = true;//now I need to add cdata for some fields only

protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
});


In ResponseTextMessage, I have several fields, the xml format I need is like



<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime> <!--I do not need cdata for this field-->
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[content]]></Content>
</xml>


How can I achieve this using xStream? Do I have any way to control how to write xml in the format I hope based on the object's specific fileds?


Thank you!


No comments:

Post a Comment