选项 #1 - 一个值类
你可以有一个Value
类,其中包含一个String
用 注释的属性@XmlMixed
。
package forum13232991;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Value {
@XmlAttribute
String type;
@XmlMixed
List<String> value;
@XmlElement(name="component")
List<Component> components;
}
选项 #2 - 多值类通过XmlAdapter
如果您希望它们成为单独的类,您可以利用XmlAdapter
:
值适配器
package forum13232991;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class ValueAdapter extends XmlAdapter<Value, Object> {
@Override
public Value marshal(Object object) throws Exception {
Value value = new Value();
if(object instanceof StructuredValue) {
StructuredValue structuredValue = (StructuredValue) object;
value.type = "structured";
value.components = structuredValue.components;
} else {
StringValue stringValue = (StringValue) object;
value.value.add(stringValue.value);
}
return value;
}
@Override
public Object unmarshal(Value value) throws Exception {
if("string".equals(value.type)) {
StringValue stringValue = new StringValue();
StringBuilder strBldr = new StringBuilder();
for(String string : value.value) {
strBldr.append(string);
}
stringValue.value = strBldr.toString();
return stringValue;
} else {
StructuredValue structuredValue = new StructuredValue();
structuredValue.components = value.components;
return structuredValue;
}
}
}
添加属性
package forum13232991;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
public class AddAttr {
@XmlJavaTypeAdapter(ValueAdapter.class)
Object value;
}
了解更多信息