有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JAXB MOXy将多个对象迭代映射到单个XML

我正在使用JAXB MOXy将java对象映射到XML。到目前为止,我只需要一次转换一个对象,这个词很好。因此,我的输出XML如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<NotificationTemplateXML template-id="1">
   <template-subject>Test Subject</template-subject>
   <template-text>Test Text</template-text>
</NotificationTemplateXML>

我现在要做的是将对象的多次迭代保存到同一个XML文件中,使其看起来像这样

<?xml version="1.0" encoding="UTF-8"?>
 <NotificationTemplateXML template-id="1">
    <template-subject>Test Subject</template-subject>
    <template-text>Test Text</template-text>
 </NotificationTemplateXML>
 <NotificationTemplateXML template-id="2">
    <template-subject>Test Subject</template-subject>
    <template-text>Test Text</template-text>
 </NotificationTemplateXML>
 <NotificationTemplateXML template-id="3">
    <template-subject>Test Subject</template-subject>
    <template-text>Test Text</template-text>
 </NotificationTemplateXML>

我的对象映射如下所示:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="NotificationTemplateXML")
public class NotificationTemplate {

    @XmlAttribute(name="template-id")
    private String templateId;
    @XmlElement(name="template-subject")
    private String templateSubject;
    @XmlElement(name="template-text")
    private String templateText;

假设我有一个“NotificationTemplate”类型的列表,我可以简单地整理列表吗?这会产生一个单独的xml文件,其中每个NotificationTemplate对象都是一个单独的“xml对象”吗

注意。同样,当我解组XML文件时,我是否希望生成“NotificationTemplate”类型的列表


共 (1) 个答案

  1. # 1 楼答案

    下面是几个不同的选项

    选项#1-处理无效的XML文档

    XML文档只有一个根元素,因此输入无效。下面是@npe给出的关于如何处理此类输入的答案:

    选项#2-创建有效的XML文档

    我建议您将XML转换为有效文档并进行处理

    具有根元素的XML文档

    我通过添加根元素修改了您的XML文档

    <?xml version="1.0" encoding="UTF-8"?>
    <NotificationTemplateXMLList>
        <NotificationTemplateXML template-id="1">
            <template-subject>Test Subject</template-subject>
            <template-text>Test Text</template-text>
         </NotificationTemplateXML>
         <NotificationTemplateXML template-id="2">
            <template-subject>Test Subject</template-subject>
            <template-text>Test Text</template-text>
         </NotificationTemplateXML>
         <NotificationTemplateXML template-id="3">
            <template-subject>Test Subject</template-subject>
            <template-text>Test Text</template-text>
         </NotificationTemplateXML>
    <NotificationTemplateXMLList>
    

    通知模板XMLList

    我向域模型引入了一个新类,它映射到新的根元素

    @XmlRootElement(name="NotificationTemplateXMLList")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class NotificationTemplates {
    
         @XmlElement(name="NotificationTemplateXML")
         private List<NotificationTemplate>  notificationTemplates;
    }