使用 jaxb 解组元素属性和文本以分隔字段

Unmarshal element attribute and text to separate fields with jaxb

如何注释 Root class 中的 externalValuecompanyId 字段,以便 "abc" 映射到 externalValue 和“123”被映射到 companyId?
我需要 @XmlJavaTypeAdapter 注释吗?在哪里?我希望如果我这样做,它可以只处理这两个字段,我可以按原样保留 titlecountryCodes 的注释。

XML:

<item>
    <externalValue companyId="123">abc</externalValue>
    <title>My Title</title>
    <country>US</country>
    <country>CA</country>
</item>

POJO:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Item {
    private String externalValue;
    private String companyId;
    @XmlElement
    private String title;
    @XmlElement(name = "country")
    public List<String> countryCodes;

    // getters and setters...
}

您必须按以下方式定义 class。

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Item {

    private CompanyIdValue companyIdValue;
    @XmlElement
    private String title;

    @XmlElement(name = "country")
    public List<String> countryCodes;

    //getter and setter
}

如果 XML 元素标签中有两个属性,您必须定义一个单独的 class。定义一个名为 CompanyIdValue 的单独 class,对于 XML 元素,您必须定义 @XmlValue 并且对于属性,您必须使用 @XmlAttribute

进行注释
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlValue;
public class CompanyIdValue {

    @XmlElement(name = "externalValue")
    private String externalValue;

    private String companyId;

    public String getExternalValue() {
        return externalValue;
    }

    @XmlValue
    public void setExternalValue(String externalValue) {
        this.externalValue = externalValue;
    }

    public String getCompanyId() {
        return companyId;
    }

    @XmlAttribute
    public void setCompanyId(String companyId) {
        this.companyId = companyId;
    }
}

我在下面提供一个测试程序,也是为了测试。

public class Test {
  public static void main(String[] args) {
    try {
      Item item = new Item();
      CompanyIdValue companyIdValue = new CompanyIdValue();
      companyIdValue.setCompanyId("SomeId");
      companyIdValue.setExternalValue("Some External value");
      item.setCompanyIdValue(companyIdValue);
      item.setCountryCodes(Arrays.asList("A", "B"));
      item.setTitle("Some Title");

      JAXBContext jaxbContext = JAXBContext.newInstance(Item.class);
      Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

      jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
      jaxbMarshaller.marshal(item, System.out);

    } catch (JAXBException e) {
      e.printStackTrace();
    }
  }
}

恐怕在一般情况下,即 JAXB 规范,仅使用注释(因此没有额外的 POJO 和一些适配器)是不可能实现的。但是,如果您碰巧使用 MOXy 作为 JAXB 实现,那么添加注释 @XmlPath 就像这样很容易:

@XmlPath("externalValue/@companyId")
private String companyId;

相关问题:Unmarshalling an XML using Xpath expression and jaxb