How to control parsing xml using xStream?

313 views Asked by At

Now I am using xStream to parse a object into xml-format String. What I hope is that when I parse xml I can do something I want to according to different fileds, say if I encounter filed A, I will add CDATA Block before it, when I encounter filed B, I will make it into upper case, something like this, and here is what I am doing now.

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 = ...;//I need to add cdata for some fields only  
                boolean isNeedUpper=...;//only some will need this

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

There are 0 answers