我正在尝试建立日历,我想将所有约会存储在XML文件中,但是,我似乎找不到解决方法。我一直在阅读有类似问题的人的答案,但似乎没有任何效果,这是我所拥有的DOM类,“ createDocument”方法的所有输入均来自文本框:
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
public class GeneradorDOM {
private Document doc;
public GeneradorDOM() throws ParserConfigurationException {
DocumentBuilderFactory factoria = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factoria.newDocumentBuilder();
doc = builder.newDocument();
}
public void createDocument(String hour, int day, int month, int year, String name,
String lastName, String title, String description,String row, String column) throws IOException{
Element root = doc.getDocumentElement();
Element appointment = doc.createElement("appointment");
/* Instead of root, I have tried with the following code as well:
Element appointments = doc.createElement("appointments");
doc.appendChild(appointments);
Element appointment = doc.createElement("appointment");
appointments.appendChild(appointment);
*/
Element nameElement = doc.createElement("name");
Text nameText = doc.createTextNode(name);
appointment.appendChild(nameElement);
nameElement.appendChild(nameText);
appointment.appendChild(nameElement);
Element lastNameElement = doc.createElement("lastname");
Text lastNameText = doc.createTextNode(lastName);
appointment.appendChild(lastNameElement);
lastNameElement.appendChild(lastNameText);
appointment.appendChild(lastNameElement);
Element dayElement = doc.createElement("day");
Text dayText = doc.createTextNode(Integer.toString(day));
appointment.appendChild(dayElement);
dayElement.appendChild(dayText);
Element monthElement = doc.createElement("month");
Text monthText = doc.createTextNode(Integer.toString(month));
appointment.appendChild(monthElement);
monthElement.appendChild(monthText);
Element yearElement = doc.createElement("year");
Text yearText = doc.createTextNode(Integer.toString(year));
appointment.appendChild(yearElement);
yearElement.appendChild(yearText);
Element hourElement = doc.createElement("hour");
Text hourText = doc.createTextNode(hour);
appointment.appendChild(hourElement);
hourElement.appendChild(hourText);
Element titleElement = doc.createElement("title");
Text titleText = doc.createTextNode(title);
appointment.appendChild(titleElement);
titleElement.appendChild(titleText);
Element descriptionElement = doc.createElement("description");
Text descriptionText = doc.createTextNode(description);
appointment.appendChild(descriptionElement);
descriptionElement.appendChild(descriptionText);
Element rowElement = doc.createElement("row");
Text rowText = doc.createTextNode(row);
appointment.appendChild(rowElement);
rowElement.appendChild(rowText);
Element columnElement = doc.createElement("column");
Text columnText = doc.createTextNode(column);
appointment.appendChild(columnElement);
columnElement.appendChild(columnText);
root.appendChild(appointment);
}
public void generateXML() throws TransformerConfigurationException, IOException, TransformerException{
TransformerFactory factoria = TransformerFactory.newInstance();
Transformer transformer = factoria.newTransformer();
Source source = new DOMSource(doc);
File file = new File("Appointments.xml");
FileWriter fw = new FileWriter(file);
PrintWriter pw = new PrintWriter(fw);
StreamResult result = new StreamResult(new FileOutputStream("Appointments.xml", true));
transformer.transform(source, result);
}
}
一种方法是能够序列化/反序列化整个约会集合。
将信息包装在Pojo中。
创建方法以将Pojos转换为Document并返回。
然后创建一个可以将pojo反序列化为xml的服务。
以下是一个粗略的实现,但仅作为示例。附带说明:使用JAXB或Jackson只需几行代码。
package examples;
public class Appointment {
private String hour;
private int day;
private int month;
private int year;
private String name;
private String lastName;
private String title;
private String description;
private String row;
private String column;
public Appointment() {
}
public Appointment(String hour, int day, int month, int year, String name, String lastName, String title,
String description, String row, String column) {
super();
this.hour = hour;
this.day = day;
this.month = month;
this.year = year;
this.name = name;
this.lastName = lastName;
this.title = title;
this.description = description;
this.row = row;
this.column = column;
}
public String getHour() {
return hour;
}
public void setHour(String hour) {
this.hour = hour;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRow() {
return row;
}
public void setRow(String row) {
this.row = row;
}
public String getColumn() {
return column;
}
public void setColumn(String column) {
this.column = column;
}
}
public class UserCalendar {
private List<Appointment> appointments = new ArrayList<Appointment>();
public UserCalendar() {
}
public List<Appointment> getAppointments() {
return appointments;
}
public void add(Appointment appointment) {
appointments.add(appointment);
}
public Document serialize() throws ParserConfigurationException {
Document doc = newDoc();
Element appElms = doc.createElement("appointments");
doc.appendChild(appElms);
for (Appointment app : appointments) {
Element child = addEmptyNode(appElms, "appointment");
addValueNode(child, "name", app.getName());
addValueNode(child, "lastname", app.getLastName());
addValueNode(child, "day", app.getDay());
addValueNode(child, "month", app.getMonth());
addValueNode(child, "year", app.getYear());
addValueNode(child, "hour", app.getHour());
addValueNode(child, "title", app.getTitle());
addValueNode(child, "description", app.getDescription());
addValueNode(child, "row", app.getRow());
addValueNode(child, "column", app.getColumn());
}
return doc;
}
private Element addValueNode(Element appointment, String name, Object value) {
Element child = addEmptyNode(appointment, name);
child.setTextContent(value.toString());
return child;
}
private Element addEmptyNode(Element appointment, String name) {
Element nameElement = appointment.getOwnerDocument().createElement(name);
appointment.appendChild(nameElement);
return nameElement;
}
private Document newDoc() throws ParserConfigurationException {
DocumentBuilderFactory factoria = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factoria.newDocumentBuilder();
return builder.newDocument();
}
public static UserCalendar deserialize(Document doc) {
UserCalendar userCalendar = new UserCalendar();
NodeList appsElms = doc.getElementsByTagName("appointment");
for (int i = 0; i < appsElms.getLength(); i++) {
Element appElm = (Element) appsElms.item(i);
String name = getNodeValue(appElm, "name");
String lastname = getNodeValue(appElm, "lastname");
int day = getNodeValueInt(appElm, "day");
int month = getNodeValueInt(appElm, "month");
int year = getNodeValueInt(appElm, "year");
String hour = getNodeValue(appElm, "hour");
String title = getNodeValue(appElm, "title");
String description = getNodeValue(appElm, "description");
String row = getNodeValue(appElm, "row");
String column = getNodeValue(appElm, "column");
Appointment appointment = new Appointment(hour, day, month, year, name, lastname, title, description, row,
column);
userCalendar.add(appointment);
}
return userCalendar;
}
private static String getNodeValue(Element appElm, String name) {
String strVal = null;
NodeList nl = appElm.getElementsByTagName(name);
if (nl != null && nl.getLength() > 0) {
strVal = nl.item(0).getTextContent();
}
return strVal;
}
private static int getNodeValueInt(Element appElm, String name) {
String str = getNodeValue(appElm, name);
return str == null ? 0 : Integer.parseInt(str);
}
}
public class UserCalendarService {
public UserCalendar load() throws ParserConfigurationException, SAXException, IOException {
File file = new File("Appointments.xml");
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document doc = builder.parse(file);
return UserCalendar.deserialize(doc);
}
public void save(UserCalendar calendar) throws IOException, TransformerException, ParserConfigurationException {
Document doc = calendar.serialize();
TransformerFactory factoria = TransformerFactory.newInstance();
Transformer transformer = factoria.newTransformer();
Source source = new DOMSource(doc);
try (FileOutputStream fos = new FileOutputStream("Appointments.xml");){
StreamResult result = new StreamResult(fos);
transformer.transform(source, result);
}
}
public void add(Appointment appointment) throws ParserConfigurationException, SAXException, IOException, TransformerException {
UserCalendar cal = load();
cal.add(appointment);
save(cal);
}
}
// Create an appointments with 2 entity
UserCalendar userCalendar = new UserCalendar();
userCalendar.add(new Appointment("20:30",31,12,2019,"newYearEve","Happy New Year Party!!!","mark","zuk","1","3"));
userCalendar.add(new Appointment("12:30",1,1,2020,"recover","Party recovery mode.","mark","zuk","2","3"));
UserCalendarService svc = new UserCalendarService();
svc.save(userCalendar);
// Append an entity to an existing appointment file
svc.add(new Appointment("8:30",7,1,2020,"work","Back to work","mark","zuk","2","3"));