代码之家  ›  专栏  ›  技术社区  ›  Rodrigo Arnaiz Piorno

jaxb删除列表标记

  •  2
  • Rodrigo Arnaiz Piorno  · 技术社区  · 6 年前

    我需要整理一个java类来获得xml,但我不知道如何删除生成的类中的标记。

    我有一个类,它有一个对象列表

    @XmlRootElement(name = "Element")
    public class Element {
        private List<Foo> foos;
        @XmlElementWrapper("fooList")
        public List<Foo> getfoos() {
            return foos;
        }
        public void setFoos(List<Foo> foos) {
            this.foos = foos;
        }
    }
    

    列表中的Foo类是:

    @XmlRootElement
    public class Foo {
        private String id;
        private String code;
        @XmlElement
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        @XmlElement
        public String getCode() {
            return code;
        }
        public void setCode(String code) {
            this.code = code;
        }
    }
    

    当编组以获取xml时,我得到以下信息:

    <Element>
      <fooList>
          <foos>
              <string1>asd</string1>
              <string2>qwe</string2>
          </foos>
          <foos>
              <string1>poi</string1>
              <string2>lkj</string2>
          </foos>
      </fooList>
    </Element>
    

    但我想不带标签foos,像这样:

    <Element>
      <fooList>
          <string1>asd</string1>
          <string2>qwe</string2>
          <string1>poi</string1>
          <string2>lkj</string2>
      </fooList>
    </Element>
    

    有人能帮我吗? 谢谢!!

    1 回复  |  直到 6 年前
        1
  •  4
  •   martidis    6 年前

    您可以这样做:

    @XmlRootElement(name = "Element")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Element {
    
        @XmlElementWrapper(name = "fooList")
        @XmlElements({
                @XmlElement(name = "id", type = Id.class),
                @XmlElement(name = "code", type = Code.class),
        })
        private List<FooItem> foos;
    
        public List<FooItem> getfoos() {
            return foos;
        }
        public void setFoos(List<FooItem> foos) {
            this.foos = foos;
        }
    }
    

    然后Id和代码类看起来很相似:

    public class Id implements FooItem {
        @XmlValue
        private String id;
    
        public Id() {}
    
        public Id(String id) {
            this.id = id;
        }
    }
    

    它们由一个没有多大作用的接口所限定:

    public interface FooItem {  }
    

    此结构将允许您按照所需的指定格式封送到xml中。

    您所面临的类结构的挑战是,类Foo有2个字段,@XmlValue只能应用于每个类的一个字段。因此,有两个字段“强制”它们代表@XmlElement,而它们又必须是xml元素的子元素。这就是为什么在xml中为列表中的每个foo实例都有“中间”foo元素的原因。