I am writing a small Java program to keep and update a list of books in my personal library. A prompt asks the user for the book’s data and the new book is saved (appended) to an XML file. The method below from the Book
class is responsible for this:
public void updateBookList(String title, String author, String publisher, int year, int numPages){
XStream xstream = new XStream(new StaxDriver());
xstream.alias("book", Book.class);
Book book = new Book(title, author, publisher, year, numPages);
String dataXml = xstream.toXML(book);
try(FileWriter fw = new FileWriter("booklist.xml", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println(dataXml);
} catch (IOException e) {
// fix later
}
}
The idea is that the file serves as a simple persistent storage of sorts, with all my books listed neatly in XML format.
However, after inserting two test books, this is what the XML looks like:
<?xml version="1.0" ?><book><title>Test1</title><author>Test1</author><publisher>Test1</publisher><year>1999</year><numPages>202</numPages><dateCreated>2024-07-17</dateCreated><dateModified>2024-07-17</dateModified></book>
<?xml version="1.0" ?><book><title>Test2</title><author>Test2</author><publisher>Test2</publisher><year>1999</year><numPages>234</numPages><dateCreated>2024-07-17</dateCreated><dateModified>2024-07-17</dateModified></book>
How can I append the data so the XML file looks something like this:
<?xml version="1.0" ?>
<book>
<title>Test1</title>
<author>Test1</author>
<publisher>Test1</publisher>
<year>1999</year>
<numPages>202</numPages>
<dateCreated>2024-07-17</dateCreated>
<dateModified>2024-07-17</dateModified>
</book>
<book>
<title>Test2</title>
<author>Test2</author>
<publisher>Test2</publisher>
<year>1999</year>
<numPages>234</numPages>
<dateCreated>2024-07-17</dateCreated>
<dateModified>2024-07-17</dateModified>
</book>
8
a well formed xml document has always one single root node, see https://en.wikipedia.org/wiki/Root_element
thus say you need to create a proper model that represents that structure, maybe you collect your books within a Books
class
<?xml version="1.0" ?>
<books>
<book>
...
</book>
<book>
...
</book>
</books>