[英]Marshalling/unmarshalling fields to tag with attributes using JAXB
假设我有班级示例:
class Example{
String myField;
}
我想以这种方式解组它:
<Example>
<myField value="someValue" />
</Example>
是否可以使用JAXB XJC以这种方式解组对象? (我在EclipseLink中了解XmlPath,但不能使用它)。
您可以在此用例中使用XmlAdapter
。 在该XmlAdapter
您将String
转换为/从具有映射到XML属性的一个属性的对象转换。
XmlAdapter
package forum12914382;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class MyFieldAdapter extends XmlAdapter<MyFieldAdapter.AdaptedMyField, String> {
@Override
public String unmarshal(AdaptedMyField v) throws Exception {
return v.value;
}
@Override
public AdaptedMyField marshal(String v) throws Exception {
AdaptedMyField amf = new AdaptedMyField();
amf.value = v;
return amf;
}
public static class AdaptedMyField {
@XmlAttribute
public String value;
}
}
例
package forum12914382;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement(name="Example")
@XmlAccessorType(XmlAccessType.FIELD)
class Example{
@XmlJavaTypeAdapter(MyFieldAdapter.class)
String myField;
}
演示
package forum12914382;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Example.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum12914382/input.xml");
Example example = (Example) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(example, System.out);
}
}
input.xml中/输出
<Example>
<myField value="someValue" />
</Example>
相关示例
是的,手动添加@XmlAttribute -Annotation或从XSD生成类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.