开发者

Marshaling arrays in JAXB

开发者 https://www.devze.com 2023-04-03 20:31 出处:网络
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 woul

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>开发者_Go百科
    <username>me</username>
</job>


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号