我创建了一个程序,它根据预制架构将 XML 数据编码到项目文件夹中的 XML 文件。但是,我对如何修改程序以将数据编码到它遇到的第一个空行而不是覆盖文件中已有的数据感到困惑。
这是我的主 Java 类的代码:
//Client Application that users can see and interact with.
package shares_system_client_application;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
public class Shares_System_Client_Application
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
//Creates instance of binded XML file.
//Shares_Info = Package name
//CurrentShares = bound XML file
Shares_Info.CurrentShares quickXML = new Shares_Info.CurrentShares();
quickXML.setCompanyName("test co");
quickXML.setCompanySymbol("DOLLAR");
Date now = new Date();
Instant current = now.toInstant();
LocalDateTime ldt = LocalDateTime.ofInstant(current, ZoneId.systemDefault());
String dateTimeString = ldt.toString();
try
{
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(dateTimeString);
quickXML.setLastShareUpdate(date2);
}
catch (Exception e)
{
System.out.println("Oopsie Poopsie");
}
quickXML.setNumOfShares(43000);
Shares_Info.CurrentShares.SharePrice quickXML2 = new Shares_Info.CurrentShares.SharePrice();
quickXML2.setCurrency("Dollar");
quickXML2.setValue(123.4f);
quickXML.setSharePrice(quickXML2);
//Marshelling code
try
{
//The JAXBContext class provides the client's entry point to the JAXB API
javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(quickXML.getClass().getPackage().getName());
//The Marshaller class is responsible for governing the process of
//serializing Java content trees back into XML data
javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller();
//Specified encoding
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8"); //NOI18N
//The name of the property used to specify whether or not the
//marshalled XML data is formatted with linefeeds and indentation.
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
File Shares_File = new File("Shares_Data.xml");
marshaller.marshal(quickXML, Shares_File);
}
catch (javax.xml.bind.JAXBException ex)
{
java.util.logging.Logger.getLogger("global").log(java.util.logging.Level.SEVERE, null, ex); //NOI18N
}
}
}
我尝试查看 JAXB 编码器选项,但找不到适用于我的问题的选项。如果您能提供任何帮助,我们将不胜感激。
最佳答案
很抱歉将这个问题搁置了这么久而没有发布解决方案。该模块刚刚完成,我正忙着完成它的工作。
我为此找到的解决方案是首先从 XML 中解码数据,将其存储在变量中,然后通过添加要添加到文件中的新数据来更新该变量。从那里开始,这只是一个使用新变量重新编码的简单情况,然后添加数据,而不会覆盖以前的数据。
关于java - JAXB 编码到 XML 文件中的第一个空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59545751/