CodyK
CodyK

Reputation: 3667

JAXB Element Wrapper for a Single Group of Elements When Marshalling

I wish to have an XML structure like this:

<?xml version="1.0" encoding="UTF-8"?>
<MSG>
   <CASE>
       <Field1></Field1>
       <Field2></Field2>
   </CASE>
</MSG>

The problem is, with the @XmlElementWrapper, I need a collection of items but there will be only 1 case item. How can I have multiple root elements, for a single collection of elements? Preferably in a single class.

I want something like this, but it throws an exception.

@XmlRootElement( name="MSG")
public class XMLStructure {

   @XmlElementWrapper(name="CASE")
   @XmlElement(name = "Field1")
   private String field1;

   @XmlElementWrapper(name="CASE")
   @XmlElement(name = "Field2")
   private String field2;
}

Upvotes: 2

Views: 1836

Answers (1)

bdoughan
bdoughan

Reputation: 149047

In the EclipseLink MOXy implementation of JAXB (JSR-222) we have an @XmlPath extension that enables you to map this as:

@XmlRootElement( name="MSG")
@XmlAccessorType(XmlAccessType.FIELD)
public class XMLStructure {

   @XmlPath("CASE/Field1/text()")
   private String field1;

   @XmlPath("CASE/Field2/text()")
   private String field2;
}

For More Information

I have written more about the @XmlPath extension on my blog:

Upvotes: 1

Related Questions