两个子元素中的JAXB序列化

时间:2013-10-01 13:18:17

标签: java jaxb

类别:

public class OddEvenSettings {
  int oddSetting1;
  int oddSetting2;
  int evenSetting1;
  int evenSetting2;
}

所需的XML

<OddEvenSettings>
  <odd setting1="0" setting2="0"/>
  <even setting1="0" setting2="0"/>
</OddEvenSettings>

如何在序列化后使用JAXB RI来注释类以获取XML?

2 个答案:

答案 0 :(得分:1)

注意:我是EclipseLink JAXB (MOXy)主管,是JAXB (JSR-222)专家组的成员。

您可以在此用例中使用MOXy的@XmlPath扩展名:

import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.*;

@XmlRootElement("OddEvenSettings")
@XmlAccessorType(XmlAccessType.FIELD)
public class OddEvenSettings {
  @XmlPath("odd/@setting1")
  int oddSetting1;

  @XmlPath("odd/@setting2")
  int oddSetting2;

  @XmlPath("even/@setting1")
  int evenSetting1;

  @XmlPath("even/@setting2")
  int evenSetting2;
}

了解更多信息

答案 1 :(得分:0)

我认为唯一的方法是创建2个新类'OddSettings'和'EvenSettings'并将'OddEvenSettings'引用到'OddSettings'和'EvenSettings'这样:

@XmlRootElement(name="OddEvenSettings")
public class OddEvenSettings {

    @XmlElement(name="odd")
    private OddSetting oddSetting = new OddSetting();

    @XmlElement(name="even")
    private EvenSetting evenSetting = new EvenSetting();

        ...
}

当然{@ 1}}和OddSettings也应注释:

EvenSettings

这产生了你所需要的东西:

@XmlAccessorType(XmlAccessType.FIELD)
public class OddSetting {
    @XmlAttribute(name="setting1")
    int oddSetting1;
    @XmlAttribute(name="setting2")
    int oddSetting2;
        ...
}

@XmlAccessorType(XmlAccessType.FIELD)
public class EvenSetting {
    @XmlAttribute(name="setting1")
    int evenSetting1;
    @XmlAttribute(name="setting2")
    int evenSetting2;
        ...
}