簡體   English   中英

使用JAXBContext將XML注釋添加到封送文件中

[英]Add XML comments into marshaled file using JAXBContext

我正在將對象編組到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  -->

謝謝

您可以利用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>

UPDATE

使用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();
    }

}

經過大量的研究,我剛剛補充說:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM