Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing List<String> with XStream with defined names

Tags:

java

xstream

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>
like image 611
Hleb Avatar asked Jan 16 '12 16:01

Hleb


2 Answers

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>
like image 151
mrembisz Avatar answered Nov 05 '22 02:11

mrembisz


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);
    }
}
like image 2
Tzig Avatar answered Nov 05 '22 00:11

Tzig