如何用可变值节点生成XML

How to generate XML with variable value nodes

我需要在我们有可变值节点的地方使用 jaxb 生成 XML。我们可以有 3 个值或 5 个值,甚至更多,例如

<custom-attribute>
  <value>Green</value>
  <value>Red</value>
</custom-attribute>

在 pojo 中我们可以像下面这样使用 List

class CustomAttribute() {
    @XmlValue
    @XmlList
    public List<String> value
}

但是用 space 分隔的字符串添加值,如下所示

<custom-attribute>Green Red</custom-attribute>

如何使用多个值节点生成所需的 XML?

我在下面提供代码,你可以试试运行。

首先,您必须创建一个 class 名为 Value 的文件,如下所示。

import javax.xml.bind.annotation.XmlValue;

public class Value {

  private String data;

  @XmlValue
  public String getData() {
    return data;
  }

  public void setData(String data) {
    this.data = data;
  }
}

然后你必须像这样创建一个名为 CustomAttribute 的class。

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;

@XmlRootElement(name = "custom-attribute")
@XmlAccessorType(XmlAccessType.PROPERTY)
class CustomAttribute {

  public List<Value> value;

  public List<Value> getValue() {
    return value;
  }

  public void setValue(List<Value> values) {
    this.value = values;
  }


}

我在下面提供测试class来检查。

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.util.ArrayList;
import java.util.List;

public class TestCustomAttribute {
  public static void main(String[] args) throws Exception {
    List<Value> valueList = new ArrayList<>();
    Value value1 = new Value();
    value1.setData("Green");
    valueList.add(value1);

    Value value2 = new Value();
    value2.setData("Red");
    valueList.add(value2);

    CustomAttribute ca = new CustomAttribute();
    ca.setValue(valueList);

    JAXBContext jaxbContext = JAXBContext.newInstance(CustomAttribute.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    // output pretty printed
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    jaxbMarshaller.marshal(ca, System.out);
  }
}

形成的XML就是这样

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<custom-attribute>
    <value>Green</value>
    <value>Red</value>
</custom-attribute>