我想将一些类存储到xml:
XStream xstream = new XStream(new DomDriver());
List<String> modules = new ArrayList<String>();
modules.add("mod1");
modules.add("mod2");
ModulesConfig modulesConfig = new ModulesConfig(modules);
xstream.processAnnotations(ModulesConfig.class);
log.info(xstream.toXML(modulesConfig));
Class ModulesConfig:
@XStreamAlias("modules-config")
public class ModulesConfig {
@XStreamAlias("moduleName")
private List<String> moduleNames;
public ModulesConfig(List<String> moduleNames) {
this.moduleNames = moduleNames;
}
public List<String> getModuleNames() {
return moduleNames;
}
public void setModuleNames(List<String> moduleNames) {
this.moduleNames = moduleNames;
}
}
结果:
<modules-config>
<moduleName>
<string>mod1</string>
<string>mod2</string>
</moduleName>
</modules-config>
但是我希望元素被命名为“moduleName”。如何配置xstream或我必须添加到类的注释?我想要这样的结果:
<modules-config>
<moduleNames>
<moduleName>mod1</moduleName>
<moduleName>mod2</moduleName>
</moduleNames>
</modules-config>
答案 0 :(得分:4)
根据您的要求,这不会得到确切的结果,但看起来更干净:
@XStreamImplicit(itemFieldName="moduleName")
private List<String> moduleNames;
产生的结果将是:
<modules-config>
<moduleName>mod1</moduleName>
<moduleName>mod2</moduleName>
</modules-config>
答案 1 :(得分:1)
您可以将moduleNames
定义为Bean,就像这样
@XStreamAlias("moduleNames")
public class ModuleNames{
@XStreamImplicit(itemFieldName="moduleName")
private List<String> moduleNames;
public List<String> getModuleNames() {
return moduleNames;
}
public void setModuleNames(List<String> moduleNames) {
this.moduleNames = moduleNames;
}
}
//then add the ModuleNames as The List<String> and hide the List Tag
@XStreamAlias("modules-config")
public class ModulesConfig {
@XStreamAlias("moduleNames")
private ModuleNames moduleNames;
public ModulesConfig(List<String> moduleNames) {
this.moduleNames = moduleNames;
}
public List<String> getModuleNames() {
return moduleNames.getModuleNames();
}
public void setModuleNames(List<String> moduleNames) {
this.moduleNames.set(moduleNames);
}
}
答案 2 :(得分:0)
我真的不知道XSteam框架,但我认为它与JAXB非常相似。在那里你可以做这样的事情。
Class ModuleConfig
@XmlRootElement(name="moduleConfig")
@XmlAccessorType(XmlAccessType.FIELD)
public class ModuleConfig {
List<ModuleName> moduleNames;
public ModuleConfig() {
moduleNames = new ArrayList<ModuleName>();
moduleNames.add(new ModuleName("mod1"));
moduleNames.add(new ModuleName("mod2"));
}
}
Class ModuleName
@XmlRootElement(name="moduleName")
@XmlAccessorType(XmlAccessType.FIELD)
public class ModuleName {
private String moduleName;
public ModuleName() { }
public ModuleName(String moduleName) {
this.moduleName = moduleName;
}
public String getModuleName() {
return moduleName;
}
}
将生成这样的输出
<moduleConfig>
<moduleNames>
<moduleName>mod1</moduleName>
</moduleNames>
<moduleNames>
<moduleName>mod2</moduleName>
</moduleNames>
</moduleConfig>