SimpleXML framework: element with element or text

柔情痞子 提交于 2019-12-04 16:12:08

My solution (not beautiful, but works and doesn't require much work to implement):

    private static class SerializerWithPreprocessor extends Persister {

        public SerializerWithPreprocessor(RegistryMatcher matcher, Format format) {
            super(matcher, format);
        }

        @Override
        public <T> T read(Class<? extends T> type, String source) throws Exception {
            source = source.replaceFirst("<Command (.*)>([[\\w||[+=]]&&[^<>]]+)</Command>", "<Command $1><Content>$2</Content></Command>");
            return super.read(type, source);
        }
    }

So I just created new Serializer class. This class use regular expressions to change Text element inside Command into normal Element. Then I can use:

@Root(name = "Command", strict = false)
public class AppCommand {

    @Element(name = "Variable", required = false)
    @Getter
    private Variable variable;

    @Element(name = "Content", required = false)
    @Getter
    private String content;
}

and during deserialization everything works like I wanted to.

Yes, Simple can't deal with this.

Command.java:

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Text;

@Root
public class Command {

    @Element(required = false, name = "Variable")
    private Variable variable;

    @Text(required = false)
    private String text;    
}

Variable.java:

class Variable {
}

SOPlayground.java:

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class SOPlayground {

    public static void main(String[] args) throws Exception {
        Serializer serializer = new Persister();
        String xml1 = "<Command><Variable/></Command>";
        String xml2 = "<Command>some text</Command>";

        serializer.validate(Command.class, xml1);
        serializer.validate(Command.class, xml2);
    }

}

This does compile but it does not run:

Exception in thread "main" org.simpleframework.xml.core.TextException: Text annotation @org.simpleframework.xml.Text(data=false, required=false, empty=) on field 'text' private java.lang.String de.lhorn.so.Command.text used with elements in class de.lhorn.so.Command

It looks like can not have both @Element and @Text members.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!