Jaxb : Append field of Request XML without modfying JAXB java class

给你一囗甜甜゛ 提交于 2019-12-24 11:16:08

问题


I am using JAXB 2.0 for the Application Deveopment which is using RestFul Webservices . Now there is a modification in the request , that is i will be getting another filed/variable in the request XML .

<Root Id="567" att="758" />   

Modified Request will be

 <Root Id="567" att="758" anotherfiledadded ="kiran" />   

My question is , is it possible to automatically append that field (anotherfiledadded)in the UserData class (Without modifying the UserData ??)

The below is my UserData class

@XmlRootElement(name = "Root")
@XmlAccessorType(XmlAccessType.FIELD)

public class UserData {

    @XmlAttribute
    private String Id;

    @XmlAttribute
    private String att;

// getters and setters 

回答1:


You can try adding the field at runtime with javassist. But... It looks like you would also require to add the Annotation @XmlAttribute and I don't know if javassist allows you to add annotations... Anyways give it a try.

See: Javassist Add




回答2:


You could use XSLT to apply an attribute into your XML document. All of the classes below are available in the JDK/JRE since Java SE 6.

JAXBContext jc = JAXBContext.newInstance(UserData.class); 
JAXBSource source = new JAXBSource(jc, myUserData);

StreamResult result = new StreamResult(System.out);

TransformerFactory tf = TransformerFactory.newInstance();
StreamSource xslt = new StreamSource("addMyAttribute.xslt");
Transformer t = tf.newTransformer(xslt);
t.transform(source, result);

If you are implementing your RESTful service using JAX-RS you could plug-in this logic via a MessageBodyWriter:



来源:https://stackoverflow.com/questions/11827978/jaxb-append-field-of-request-xml-without-modfying-jaxb-java-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!