【问题标题】:Reuse element/class with JAXB unmarshalling通过 JAXB 解组重用元素/类
【发布时间】:2018-08-22 15:25:10
【问题描述】:

我有这个 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;
  }
}

如何在“longevity”类/元素和“reproduction/breedingInterval”类/元素中重用这些类?还是我必须复制它们并使用相同的代码创建 LongevityMin 和 BreedingMin?来自上层阶级的 setter/getter 呢?

【问题讨论】:

    标签: java xml jaxb code-reuse


    【解决方案1】:

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-15
      • 1970-01-01
      • 2013-11-19
      • 2018-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多