我已经创建了 xml 文件,但问题是当我添加其他数据时它被覆盖了..我需要一个代码来创建一个新的 xml 文件,如果它不存在,或者如果它退出,则附加到一个 xml 文件......我正在创建一个记录交易记录的日志文件
这是代码:
import java.io.*;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
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.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Log_XML {
static String transaction_type, shop_no, terminal_no;
static int id = 0;
public static void main(String[] args) throws IOException, DOMException {
System.out.println("Enter Id : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
id = Integer.parseInt(br.readLine());
System.out.println("Enter Transaction type : ");
transaction_type = br.readLine();
System.out.println("Shop no : ");
shop_no = br.readLine();
System.out.println(“Terminal no : “);
terminal_no = br.readLine();
write_XML_File(id);
}
public static void write_XML_File(int id) {
String id_val = Integer.toString(id);
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element log1 = doc.createElement("log");
doc.appendChild(log1);
Attr attr = doc.createAttribute("id");
attr.setValue(id_val);
log1.setAttributeNode(attr);
Element transaction_type1 = doc.createElement("transaction_type");
transaction_type1.appendChild(doc.createTextNode(transaction_type));
log1.appendChild(transaction_type1);
Element shop_no1 = doc.createElement("shop_no");
shop_no1.appendChild(doc.createTextNode(shop_no));
log1.appendChild(shop_no1);
Element terminal_no1 = doc.createElement("terminal_no");
terminal_no1.appendChild(doc.createTextNode(terminal_no));
log1.appendChild(terminal_no1);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("D:/log_file.xml"));
transformer.transform(source, result);
System.out.println("File saved!");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
}