【问题标题】:jaxb delete list tagjaxb 删除列表标签
【发布时间】:2018-02-26 13:02:33
【问题描述】:

我需要编组一个 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>

谁能帮帮我? 非常感谢!!

【问题讨论】:

  • 课程是为你生成的?你能改变它们的结构吗?你愿意吗?
  • 是的,这些类是我生成的,我可以更改它们

标签: java xml jaxb marshalling


【解决方案1】:

你可以这样做:

@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 和 Code 类看起来很相似:

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 只能应用于每个类的一个字段。因此,拥有 2 个字段“强制”它们代表 @XmlElement,而它们又必须是 xml 元素的子元素。这就是为什么您在 xml 中为 List 中的每个 Foo 实例都有“中间” foo 元素的原因。

【讨论】:

  • 谢谢@mart,它解决了我的问题,我现在得到了其他的,但我正在解决它们。
  • @RodrigoArnaizPiorno 不用担心!如果您在其他问题上需要任何帮助,我很乐意提供帮助
猜你喜欢
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多