我需要使用jaxb生成XML,在jaxb中我们有变量值节点。我们可以有3个值或5个值,甚至更多
<custom-attribute>
<value>Green</value>
<value>Red</value>
</custom-attribute>在pojo中,我们可以使用List,如下所示
class CustomAttribute() {
@XmlValue
@XmlList
public List<String> value
}但这会将值与空格分隔的字符串相加,如下所示
<custom-attribute>Green Red</custom-attribute>如何生成具有多个值节点的所需XML?
发布于 2019-06-07 17:26:44
我提供了下面的代码,你可以试着运行。
首先,您必须创建一个名为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的类,如下所示。
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;
}
}我提供了下面的Test类来检查。
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>https://stackoverflow.com/questions/56490752
复制相似问题