JAXB 中的编组数组

发布于 2024-12-03 05:03:12 字数 923 浏览 0 评论 0原文

我对 Job 对象进行编组没有问题,但是当我尝试对 Job 数组进行编组时,我得到了一个错误的 XML。看来我需要创建一个类似的包装元素。我不知道怎么做,我希望在这方面得到一些帮助。

MyClass:

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

用法:

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

结果: 这是一个无效的 XML 文件

<?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>

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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尘曦 2024-12-10 05:03:12

即使 JAXB 不会生成复数形式的 XML 文件 您仍然会有多个作业元素,这些元素无效,因为只允许一个根元素。

我看到两个解决方案。

  1. 首选解决方案:创建一个 JAXB bean 作业(您的新根元素)来保存作业数组,然后作为奖励,您可以轻松地解组 XML。
  2. 追加 <工作>到循环之前的 StringWriter 和 在循环之后并过滤掉其余的

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文