JAXB Annotation for Using Child Elements

I do marshaling and send out messages. I have this type of XML:

@XMLAccesorType(AccesorType.FIELD) @XMLType(name="Header") public class Header{ @XMLElement(name="messageId") private String messageId; //getters and setters } 

and I have a message type:

 <Message> <messageId>1111</messageId> </Message> 

I want to highlight the MessageId type for the independence class, because I use it many times in different messages:

 @XMLAccesorType(AccesorType.FIELD) @XMLType(name="MessageIdType") public class MessageIdClass{ @XMLElement(name="messageId") private String messageId; //getters and setters } 

But then I have an unwanted tag that ends with MessageId. I want to:

 <Message> <MessageId>1111</MessageId> </Message> 

But received:

 <Message> <MessageIdType> <MessageId>1111</MessageId> </MessageIdType> </Message> 

Also, messages cannot inherit some base class with the messageId field. Can I write something like this?

 //inside Message @SomeAnnotation(useOnlyChildFields=true) MessageIdClass msgId; 
+4
source share
2 answers

You can do:

 @XmlType(name="MessageIdType") public class MessageIdClass{ @XmlValue private String messageId; } 

This will create a simple type.

If you need more than one property, or if the one property you need cannot be mapped to a simple type, you can create a type with several properties, and then use:

 new JAXBElement<MessageIdClass>( new QName("http://foo/bar", "ElementOfThisType"), MessageIdClass.class, null, object_of_type_MessageIdClass); 

to create elements of this type. This is usually done in ObjectFactory using a method that receives a MessageIdClass object annotated with @XmlElementDecl .

+3
source

I believe that @XmlValue is what you are looking for, this will eliminate the messageId element:

 @XmlAccesorType(XmlAccesorType.FIELD) @XmlType(name="MessageIdType") public class MessageIdClass{ @XmlValue private String messageId; //getters and setters } 

Additional Information

+1
source

All Articles