简体   繁体   English

如何使用jaxb将XML数据添加到另一个数据并将其存储在单个文件中?

[英]How to add XML data to another and store them in a single file using jaxb?

I'm using jaxb to make xml file and store it in my pc, and i want when making another file to store it in addition to the first file in the same xml file that is on my pc, for example this is the first file: 我正在使用jaxb制作xml文件并将其存储在我的PC中,并且我希望在制作另一个文件时除了将第一个文件存储在与我PC相同的xml文件中之外,例如,这是第一个文件:

<File>
   <thing1>
   </thing1>
</file>

And i want the second file to be like that : 我希望第二个文件是这样的:

 <File>
       <thing1>
       </thing1>
       <thin2g>
       </thing2>
    </file>

And that's the Java code i use for marshaling: 这就是我用于封送处理的Java代码:

public ConfList(Object obj){
        this.obj = obj;
    }

    public void addToLXML() throws IOException, JAXBException {

        File file = new File(fileName);
        JAXBContext jaxbContext = JAXBContext.newInstance(Xml.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(obj, file);
        jaxbMarshaller.marshal(obj, System.out);

    }

If I understand your question correctly, you want to be able to add new elements to an existing XML file? 如果我正确理解了您的问题,您是否希望能够向现有XML文件添加新元素? So the first time you create the file, the "thing1" element would be added, and the second time the program is run, the "thing2" element would be added? 因此,第一次创建文件时,将添加“ thing1”元素,而第二次运行程序时,将添加“ thing2”元素?

Assuming this is the case, the best way to do this would be to unmarshal the existing file into an object that contains an annotated list of "thing" elements (assuming they are the same type or share a common parent class). 假设是这种情况,最好的方法是将现有文件解组到包含“事物”元素的带注释列表的对象中(假定它们是相同类型或共享一个公共的父类)。 Then simply add your new "thing" to the list, and marshal it back to file. 然后,只需将新的“事物”添加到列表中,然后将其编组回文件即可。

If this didn't address your question, please clarify what you are looking for, and I'll see what I can do to help! 如果这不能解决您的问题,请说明您要寻找的内容,我将为您提供帮助!

Steve 史蒂夫

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM