[英]How to marshal a java List with out XML root element using JAXB?
我有龐大的java對象列表,希望使用JAXB編組沒有根元素的列表。 有可能嗎?
我有一個這樣的清單
List<Element> elements = new ArrayList<Element>
Expected Output:
<element>
----------
---------
</element>
<element>
---------
---------
<element>
我怎么能以這種方式編組,
任何參考或提示將不勝感激。
您可以遍歷列表單獨編組每個項目。 您需要在Marshaller
上設置JAXB_FRAGMENT
屬性,以防止寫出XML標頭。 您只需要為此用例創建一次JAXBContext
和Marshaller
。
import java.io.FileOutputStream;
import java.util.*;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Element.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
List<Element> elements = new ArrayList<>();
elements.add(new Element());
elements.add(new Element());
try(FileOutputStream fos = new FileOutputStream("src/forum18509018/out.txt")) {
for(Element element : elements) {
marshaller.marshal(element, fos);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.