简体   繁体   English

用Java写入XML文件不起作用

[英]Writing to XML file by java not working

I am trying to create node named Log which contains these tags date,message,type. 我正在尝试创建名为Log的节点,其中包含这些标记的日期,消息,类型。 I have written a function that does my job. 我编写了一个可以完成工作的函数。 Somehow it doesn't generate any exceptions, but still it is not working. 它以某种方式不会生成任何异常,但是仍然无法正常工作。 I am not getting that tag. 我没有那个标签。 Can anyine tell me where I have gone wrong? 有谁能告诉我哪里出了问题?

void writeToXML(String date,String message,String type)
{
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse("D:\\Log.xml");
        Element root = document.getDocumentElement();
        Element newlog = document.createElement("log");
        Element name = document.createElement("date");
        name.appendChild(document.createTextNode(date));
        Element name1 = document.createElement("type");
        name1.appendChild(document.createTextNode(type));
        Element name2 = document.createElement("message");
        name2.appendChild(document.createTextNode(message));
        newlog.appendChild(name);
        newlog.appendChild(name1);
        newlog.appendChild(name2);
        root.appendChild(newlog);
        System.out.println(root.getTextContent()+"     "+document.getTextContent());

        System.out.println("Dude working");

    }
    catch(Exception e)
    {
        System.out.println(e.toString());
    }

}

You need a TransformerFactory to save the changes. 您需要一个TransformerFactory来保存更改。

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File("D:\\Log.xml"));
transformer.transform(source, result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM