如何在Java中将xml文件保存到本地桌面

时间:2011-04-16 02:14:00

标签: java xml

我创建了一个xml文件,我想将它保存到我的桌面,但我不知道如何做这类事情。

到目前为止,这是我的代码:

// 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);

谢谢,

1 个答案:

答案 0 :(得分:4)

看起来你已经想出了为文件构建和编写XML,并且真的在询问如何在用户的桌面上创建文件。

如果是,请阅读In java under Windows, how do I find a redirected Desktop folder?

的已接受答案

顺便说一句,该解决方案不是Windows特定的。