Imrul
Imrul

Reputation: 3526

How to generate XML with variable value nodes

I need to generate XML using jaxb where we have variable value nodes. We can have 3 values or 5 values or even more like

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

In the pojo we can use List like bellow

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

but that adds values with space separated string like bellow

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

How can I generate desired XML with multiple value nodes?

Upvotes: 1

Views: 331

Answers (1)

Sambit
Sambit

Reputation: 8021

I provide below the code, you can try to run.

First you have to create a class called Value as given below.

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;
  }
}

Then you have to create a class called CustomAttribute like this.

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;
  }


}

I provide below the Test class to check.

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);
  }
}

The formed XML will be like this.

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

Upvotes: 1

Related Questions