special0ne
special0ne

Reputation: 6263

Marshaling arrays in JAXB

I have no problem to marshal Job objects but when i try to marhsal an array of Job i am getting a bad XML. It seems like i need to create a wrapping element something like . I dont know how and I would love some help on this one.

MyClass:

@XmlRootElement(name = "job")
class Job{
  private String username;
  private Calendar previousFireTime;
}

Usage:

Job[] jobs = service.getJobs( ... );
    StringWriter sw = new StringWriter();
    for (int i=0 ; i<jobs.length ; i++)
        RESTUtils.getMarshaller(Job.class).marshal(jobs[i], sw);

Result: which is an invalid XML file

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<job>
    <nextFireTime>2011-09-06T18:45:00-07:00</nextFireTime>
    <username>me</username>
</job>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<job>
    <nextFireTime>2011-09-06T18:48:00-07:00</nextFireTime>
    <username>me</username>
</job>

Upvotes: 3

Views: 1343

Answers (1)

user425367
user425367

Reputation:

Even if JAXB wouldn't produce an XML file with pluralis of <?xml version="1.0" encoding="UTF-8" standalone="yes"?> you would still have several job element which would not be valid as only one root element is allowed.

I see two solutions.

  1. Preferred solution: Create a JAXB bean jobs (your new root element) which holds the job array then as a bonus you can unmarshal the XML easily to.
  2. Append <?xml...> <jobs> to the StringWriter before the loop and </jobs> after the loop and filter out the rest of the <?xml lines.

Upvotes: 3

Related Questions