I want to store some class to 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;
}
}
Result:
<modules-config>
<moduleName>
<string>mod1</string>
<string>mod2</string>
</moduleName>
</modules-config>
But I want elements were named "moduleName". How to configure xstream or what annotations I must to add to class? I want such result:
<modules-config>
<moduleNames>
<moduleName>mod1</moduleName>
<moduleName>mod2</moduleName>
</moduleNames>
</modules-config>
This won't have the exact result as you requested but seems cleaner:
@XStreamImplicit(itemFieldName="moduleName")
private List<String> moduleNames;
The produced result will be:
<modules-config>
<moduleName>mod1</moduleName>
<moduleName>mod2</moduleName>
</modules-config>
You can define the moduleNames
as a Bean,Like this
@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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With