我的XML定义为
<ROOT>
<CHILD1 VALUE=""/>
<CHILD2 VALUE=""/>
</ROOT>
有什么方法可以将 VALUE 属性作为元素的值提取出来,而不是将 CHILD1 视为具有 VALUE 属性的 ComplexType 以使其适合此 pojo?
@XmlRootElement(name="ROOT")
public class Root {
@XmlElement(name="CHILD1")
private String child1;
@XmlElement(name="CHILD2")
private String child2;
}
JAXB中有一些表态化绑定功能 https://docs.oracle.com/javase/tutorial/jaxb/intro/custom.html:但我想对于不那么重要的事情来说,这将相当复杂。
如果你的Java Pojos没有生成,你可以简单地添加方法直接访问子字段,例如Root.getChild1String((,它将调用Root.getChild1((.getValue((
或者,您可以更改 xml 架构。
我最终编写了一个适配器来转换反序列化的属性。
@XmlElement(name = "CHILD1")
@XmlJavaTypeAdapter(ValueAdapter.class)
private String child1;
public class ValueAdapter extends XmlAdapter<Object, String> {
private static String VALUE = "VALUE";
@Override
public String unmarshal(Object e) throws Exception {
if (e instanceof ElementNSImpl && ((ElementNSImpl)e).hasAttribute(VALUE)) {
return ((ElementNSImpl)e).getAttribute(VALUE);
}
return null;
}
@Override
public Object marshal(String s) throws Exception {
return null;
}
}