java - 如何使用 JAXB 编码没有 XML 根元素的 java 列表?

标签 java xml jaxb

我有大量的 java 对象列表,想使用 JAXB 编码没有根元素的列表。有可能吗?

我有一个类似这样的列表

List<Element> elements = new ArrayList<Element>

Expected Output:
<element>
  ----------
  ---------
</element>
<element>
  ---------
  ---------
<element>

我怎样才能以这种方式编码,

任何引用或提示将不胜感激。

最佳答案

您可以遍历列表,单独编码每个项目。您需要在 Marshaller 上设置 JAXB_FRAGMENT 属性,以防止 XML header 被写出。对于此用例,您只需创建一次 JAXBContextMarshaller

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);
           }
        }
    }

}

关于java - 如何使用 JAXB 编码没有 XML 根元素的 java 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18509018/

相关文章:

java - Google 自定义搜索 API : Daily Limit for Unauthenticated Use Exceeded. 继续使用需要注册

java - gae java sdk/eclipse 插件的本地主机开发数据存储在哪里?

xml - Grails:将XML节点添加为插件的doWithWebDescriptor中的最后一个web.xml节点

jaxb - 使用 JAXB 在 OSGi 独立框架中获取 ClassCastException

java - 在 java-8 中解码 xml 时出错 "secure-processing org.xml.sax.SAXNotRecognizedException causing java.lang.IllegalStateException"

java - 在转换为 Java 对象之前检查 xsd datetime 是否有定义的时区

java - System.getenv 没有获取 ~/.bash_profile 中定义的变量

javascript - 通过 WebSocket (BinaryWebSocketFrame) 和 Netty 上传文件

javascript - Highcharts 分组类别数据 csv

c# - XDocument.Descendants ("somethinghere").Count() 方法不存在