2012-07-03 48 views
1

我正在使用JAXB MOXy將我的java對象映射到XML。直到現在,我只需要一次轉換1個對象,而且這個詞很好。所以,我的輸出XML看起來是這樣的:JAXB MOXy映射多個對象迭代到單個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'類型的列表,我可以簡單地列出這個列表嗎?是否會將每個NotificationTemplate對象生成一個單獨的xml文件作爲單獨的「XML對象」?

注意:同樣,當我解析XML文件時,我期望生成一個Type'NotificationTemplate'的列表?

回答

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> 

NotificationTemplateXMLList

我介紹了一個新的類到你的域模型映射到新的根元素。

@XmlRootElement(name="NotificationTemplateXMLList") 
@XmlAccessorType(XmlAccessType.FIELD) 
public class NotificationTemplates { 

    @XmlElement(name="NotificationTemplateXML") 
    private List<NotificationTemplate> notificationTemplates; 
} 
+1

嗨布萊斯(再次),感謝您的出色答案。 – tarka

+0

如果對象在您聲明的列表中有所不同,該怎麼辦?我有類似的情況:如何在JAXB中有多個同名的節? 你能幫忙嗎? –