Writing from Java to an XML document - Simple

筅森魡賤 提交于 2019-12-06 02:49:55

You should use a decent XML API. For example, here's an example using JDOM:

import java.io.*;

import org.jdom2.*;
import org.jdom2.input.*;
import org.jdom2.output.*;

public class Test {
    public static void main(String args[]) throws IOException, JDOMException {
        File input = new File("input.xml"); 
        Document document = new SAXBuilder().build(input);
        Element element = new Element("event");
        element.setAttribute("title", "foo");
        // etc...
        document.getRootElement().addContent(element);

        // Java 7 try-with-resources statement; use a try/finally
        // block to close the output stream if you're not using Java 7
        try(OutputStream out = new FileOutputStream("output.xml")) {
            new XMLOutputter().output(document, out);
        }
    }
}

It's really not that hard... and it'll be much, much more robust than writing it out manually. (For example, this will do the right thing if your event title contains "&" - whereas your code would have produced invalid XML.)

If you like fluent api, then you can use JOOX:

File file = new File("projects.xml");

Document document = $(file).document();

Comment eventComment = document.createComment("Above event added by: "
        + System.getProperty("user.name") + "\n" +
        " on: " + month + "/" + day + "/" + year);

document = $(file)
        .xpath("//data")
        .append($("event",
                $("title", "titleFieldUI"),
                $("start", monthLongUI + " " + dayLongUI + " " + yearLongUI + " 00:00:00 EST"),
                $("isDuration", "true"),
                $("color", sValue),
                $("end", monthLong1UI + " " + dayLong1UI + " " + yearLong1UI + " 00:00:00 EST")))
        .append($(eventComment))
        .document();

Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult(file);
Source input = new DOMSource(document);

transformer.transform(input, output);

or XMLBuilder

XMLBuilder builder = XMLBuilder.parse(
        new InputSource(new FileReader("C:/Documents and Settings/blank/My Documents/test/test.txt")))
        .xpathFind("//data")
        .e("event")
        .a("title", titleFieldUI)
        .a("start", monthLongUI + " " + dayLongUI + " " + yearLongUI + " 00:00:00 EST")
        .a("isDuration", "true")
        .a("color", sValue)
        .a("end", monthLong1UI + " " + dayLong1UI + " " + yearLong1UI + " 00:00:00 EST")
        .up()
        .comment("Above event added by: " + System.getProperty("user.name") + "\n" +
                " on: " + month + "/" + day + "/" + year);

PrintWriter writer = new PrintWriter(new FileOutputStream("C:/Documents and Settings/blank/My Documents/test/test.txt"));
builder.toWriter(writer, new Properties());

You could use JOOX. This is how you would do an append:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document doc = parser.parse("/pathToXML");

JOOX.$(doc).append("<newNode>data<newNode>");

By default the $(doc) will load the root node. If you want an inner node you can use the find() method. The library is not documented very well but being open source you can always directly check the sources.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!