通过JAXB解组重用元素/类

时间:2018-08-22 15:25:11

标签: java xml jaxb code-reuse

我有这个XML结构:

<?xml version="1.0" encoding="UTF-8"?>
<specie name="Puma concolor" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="species.xsd">
<longevity>
    <lifeSpan type="wild">
      <min type="y">18</min>
      <max type="y">20</max>
    </lifeSpan>
    <lifeSpan type="captivity">
      <avg type="y">20</avg>
    </lifeSpan>
  </longevity>
<reproduction>
    <matingSystem>polygamous/polygynous</matingSystem>
    <gestation>
      <min type="d">84</min>
      <max type="d">106</max>
    </gestation>
  </reproduction>  
</specie>

我已经创建了三个类Min,Max和Avg,如下所示:

package speciejaxb;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;

@XmlType(name = "max")
public class Max {

  private int _value;

  public int getValue() {
    return _value;
  }

  @XmlValue
  public void setValue(int value) {
    this._value = value;
  }

  private String _type;

  public String getType() {
    return _type;
  }

  @XmlAttribute
  public void setType(String type) {
    this._type = type;
  }
}

我如何在“长寿”类/元素和“ reproduction / breedingInterval”类/元素内重用此类?还是我必须复制它们并使用相同的代码创建LongevityMin和BreedingMin?上层社会的二传手/ getter呢?

1 个答案:

答案 0 :(得分:0)

SimpleXml可以做到。首先介绍一些POJO:

public class Specie {
    @XmlAttribute
    public String name;
    @XmlWrapperTag("longevity")
    @XmlName("lifeSpan")
    public List<LifeSpan> lifespans;
    public Reproduction reproduction;
}
public class LifeSpan {
    @XmlAttribute
    public String type;
    public Max max;
    public Max min;
    public Max avg;
}
public class Max {
    @XmlAttribute
    public String type;
    @XmlTextNode
    public int value;
}
public class Reproduction {
    public String matingSystem;
    public Gestation gestation;
}
public class Gestation {
    public Max max;
    public Max min;
}

请注意,我在各个地方都重复使用了Max类,但是我不认为它应该被称为Max。 接下来,我们将XML序列化为一个对象并打印一些值:

final SimpleXml simple = new SimpleXml();
final Specie s = simple.fromXml(xml, Specie.class);
System.out.println(s.reproduction.gestation.min.value);
System.out.println(s.lifespans.get(1).avg.value);

这将打印:

84
20

SimpleXml位于Maven中央:

<dependency>
    <groupId>com.github.codemonstur</groupId>
    <artifactId>simplexml</artifactId>
    <version>1.5.5</version>
</dependency>