1

我有这门课

@XStreamAlias("myConfig")
public class MyConfig {
    ... // other properties

    // What do I put here? 
    private List<String> includes;
}

我想要这个输出:

<myConfig>
    ...
    <includes>
        <includes>foo</include>
        <includes>bar</include>
    </includes>
</myConfig>

这不起作用,因为元素丢失了:

    @XStreamImplicit(itemFieldName = "include") // Loses <includes> element
    private List<String> includes;
4

2 回答 2

2

由于您的问题带有标记并基于您的评论。

@BlaiseDoughan 是的,也是 jaxb:从长远来看,我可能会考虑从 xstream 切换到 jaxb,因为 JAXB 可以生成 XSD。

以下是使用JAXB (JSR-222)实现时的样子:

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlRootElement
public class MyConfig {

    private List<String> includes;

    @XmlElementWrapper
    @XmlElement(name = "include")
    public List<String> getIncludes() {
        return includes;
    }

    public void setIncludes(List<String> includes) {
        this.includes = includes;
    }

}

了解更多信息

于 2013-01-25T12:27:10.743 回答
1

要获得您正在寻找的确切 xml 结构,需要对您的代码进行微调。基本上,您需要一个包含值列表的包含包装器对象。

这是我生成xml的代码

public class XSTreamAnnotTest {

    static class Includes {

        @XStreamImplicit(itemFieldName = "include")
        private List<String> include;

        Includes(List<String> include) {
            this.include = include;
        }
    }

    @XStreamAlias("myConfig")
    static class MyConfig {

        private Includes includes;

        public MyConfig(Includes includes) {
            this.includes = includes;
        }

    }

    public static void main(String args[]) throws Exception {
        XStream stream = new XStream();
        stream.processAnnotations(MyConfig.class);
        ArrayList<String> list = new ArrayList<String>();
        list.add("foo");
        list.add("bar");
        Includes cu = new Includes(list);

        MyConfig msg = new MyConfig(cu);
        System.out.println(stream.toXML(msg));
    }
}
于 2013-02-01T00:59:40.883 回答