使用JAXBContext将XML注释添加到封送文件中

时间:2013-06-05 16:44:37

标签: xml jaxb marshalling

我正在将对象编组到XML文件中。如何在该XML文件中添加注释

ObjectFactory factory = new ObjectFactory();
JAXBContext jc = JAXBContext.newInstance(Application.class);
Marshaller jaxbMarshaller = jc.createMarshaller();
jaxbMarshaller.marshal(application, localNewFile);          
jaxbMarshaller.marshal(application, System.out);

有一些想法

<!-- Author  date  -->

由于

2 个答案:

答案 0 :(得分:2)

您可以利用JAXB和StAX并执行以下操作:

<强>演示

如果您希望文档开头的注释可以在使用JAXB编组对象之前将它们写出到目标。您需要确保将Marshaller.JAXB_FRAGMENT属性设置为true以防止JAXB编写XML声明。

import javax.xml.bind.*;
import javax.xml.stream.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        XMLStreamWriter xsw = xof.createXMLStreamWriter(System.out);

        xsw.writeStartDocument();
        xsw.writeComment("Author  date");

        JAXBContext jc = JAXBContext.newInstance(Foo.class);

        Foo foo = new Foo();
        foo.setBar("Hello World");

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.marshal(foo, xsw);

        xsw.close();
    }

}

域名模型(Foo)

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Foo {

    private String bar;

    public String getBar() {
        return bar;
    }

    public void setBar(String bar) {
        this.bar = bar;
    }

}

<强>输出

<?xml version="1.0" ?><!--Author  date--><foo><bar>Hello World</bar></foo>

<强>更新

使用StAX方法,输出将不会被格式化。如果您想要格式化,以下内容可能会更适合您:

import java.io.OutputStreamWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        OutputStreamWriter writer = new OutputStreamWriter(System.out, "UTF-8");
        writer.write("<?xml version=\"1.0\" ?>\n");
        writer.write("<!--Author  date-->\n");

        JAXBContext jc = JAXBContext.newInstance(Foo.class);

        Foo foo = new Foo();
        foo.setBar("Hello World");

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.marshal(foo, writer);

        writer.close();
    }

}

答案 1 :(得分:1)

经过大量研究后,我刚刚补充道:

System.out.append("your comments");           
System.out.flush();
System.out.append("\n");           
System.out.flush();
jaxbMarshaller.marshal(application, localNewFile);
jaxbMarshaller.marshal(application, System.out);