问题
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