【发布时间】:2023-03-07 23:06:01
【问题描述】:
我在我的项目中处于编组一个 pojo 对象并首次将输出写入 XML 文件的情况,然后在同一文件中附加具有不同值但相同节点和子节点的相同编组对象。这是以下代码-
**Person person = new Person(personList.get(id));**
try {
File file = new File("D:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(person, file);
jaxbMarshaller.marshal(person, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
Output:
file.xml created with bellow structure -
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
<country>India</country>
<id>1</id>
<name>Aatif Hasan</name>
</person>
随着 Person 构造函数中的“id”发生变化,并且下次使用不同的属性值对 Person 对象进行封送处理时,“file.xml”文件将被覆盖,并且我丢失了之前的输出。只是我想在每次“id”获取更改时附加封送的 Person 对象。即对象属性设置为不同的值。例如..
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
<country>India</country>
<id>1</id>
<name>Aatif Hasan</name>
</person>
<person>
<country>USA</country>
<id>2</id>
<name>ABC</name>
</person>
<person>
<country>UK/country>
<id>3</id>
<name>XYZ</name>
</person>
.
.
.
and so on..
请任何人提示我如何做到这一点。任何帮助表示赞赏。我试图在stackoverflow Q/A列表上搜索类似的场景,但找不到。
热烈的问候。!!
【问题讨论】:
-
你可以使用列表。
-
您可以尝试设置 jaxb.fragment 选项并在调用 marshall 时使用文件输入流。
-
但是 XML 的例子是无效的。您需要有一个根节点。