SimpleXML框架:带元素或文本的元素 [英] SimpleXML framework: element with element or text
问题描述
我必须解析XML,它可以有两种形式:
I must to parse XML which can have two forms:
<Command><Variable/></Command>
或:
<Command>some text</Command>
我该怎么做?当我尝试在负责命令的类中声明
@Element
和 @Text
时解析当我尝试将XML解析为此类的实例时抛出异常。
How can I do this? When I try to declare both @Element
and @Text
in class responsible for Command
parsing then exception is thrown when I try to parse XML to instance of this class.
我当前的代码版本:
@Root(name = "Command", strict = false)
public class AppCommand {
@Element(name = "Variable", required = false)
@Getter
private Variable variable;
@Text(required = false)
@Getter
private String content;
}
例外是:文本注释@ org.simpleframework.xml.Text(required = false,empty =,data = false)字段'content'私有java.lang.String com.example.AppCommand.content与类中的元素一起使用com.example.AppCommand
推荐答案
我的解决方案(不漂亮,但有效,不需要很多工作要实现):
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);
}
}
所以我刚创建了新的Serializer类。此类使用正则表达式将 Command
中的 Text
元素更改为普通元素
。然后我可以使用:
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.
这篇关于SimpleXML框架:带元素或文本的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!