如何在Java中将xml文件保存到本地桌面
我已经创建了一个xml文件,我想把它保存到我的桌面上,但我不知道该怎么做 以下是我迄今为止的代码:如何在Java中将xml文件保存到本地桌面,java,xml,Java,Xml,我已经创建了一个xml文件,我想把它保存到我的桌面上,但我不知道该怎么做 以下是我迄今为止的代码: // create xml DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document testDoc = bui
// create xml
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document testDoc = builder.newDocument();
Element bo = testDoc.createElement("bo");
bo.setAttribute("type", "Employee");
bo.setAttribute("id", emp.getId());
testDoc.appendChild(bo);
Element username = testDoc.createElement("username");
username.setTextContent(emp.getUsername());
bo.appendChild(username);
Element passHash = testDoc.createElement("passwordHash");
passHash.setTextContent(emp.getPasswordHash());
bo.appendChild(passHash);
Element passwordSalt = testDoc.createElement("passwordSalt");
passwordSalt.setTextContent(emp.getPasswordSalt());
bo.appendChild(passwordSalt);
Element name = testDoc.createElement("name");
name.setTextContent(emp.getName());
bo.appendChild(name);
Element lastLogin = testDoc.createElement("lastLogin");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("date = " + emp.getLastLogin());
String date = df.format(emp.getLastLogin());
lastLogin.setTextContent(date);
bo.appendChild(lastLogin);
DOMSource source = new DOMSource(testDoc);
PrintStream ps = new PrintStream(emp.getId() + ".xml");
StreamResult result = new StreamResult(ps);
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(source, result);
谢谢,看起来您已经找到了构建XML并将其写入文件的方法,并且正在询问如何在用户桌面上创建该文件 如果是,请阅读已接受的答案
顺便说一句,该解决方案不是特定于Windows的。看起来您已经找到了构建XML并将其写入文件的方法,并且正在询问如何在用户桌面上创建该文件 如果是,请阅读已接受的答案
顺便说一句,这个解决方案并不是针对Windows的。我知道这看起来很奇怪,但我真的很兴奋,真的超出了我的编程舒适区。谢谢+1、解释问题(并给出解决方案)。所有的XML代码让我陷入了白费力气。我想知道为什么答案还没有被接受?我知道这看起来很奇怪,但我真的很兴奋,真的超出了我的编程舒适区。谢谢+1、解释问题(并给出解决方案)。所有的XML代码让我陷入了白费力气。我想知道为什么答案还没有被接受?