【问题标题】:Writing from Java to an XML document - Simple从 Java 写入 XML 文档 - 简单
【发布时间】:2013-04-04 20:09:42
【问题描述】:

我知道在 stackoverflow 上从 Java 写入 XML 有很多问题,但这太复杂了。我觉得我有一个非常简单的问题,我就是想不通。

所以我有一个程序需要大量用户输入,我目前正在创建并附加一个带有结果的文本文档。我将在这里发布我的编写器代码:

 PrintWriter out = null;
         try {
             out = new PrintWriter(new BufferedWriter(new FileWriter("C:/Documents and Settings/blank/My Documents/test/test.txt", true)));
             out.println("");
             out.println("<event title=\""+titleFieldUI+"\"");
             out.println("  start=\""+monthLongUI+" "+dayLongUI+" "+yearLongUI+" 00:00:00 EST"+"\"");            
             out.println("  isDuration=\"true\"");
             out.println("  color=\""+sValue+"\"");
             out.println("  end=\""+monthLong1UI+" "+dayLong1UI+" "+yearLong1UI+" 00:00:00 EST"+"\"");
             out.println("  "+descriptionUI);
             out.println("");
             out.println("</event>");
             out.println("  <!-- Above event added by: " +System.getProperty("user.name")+" " +
                        "on: "+month+"/"+day+"/"+year+" -->");       
         }catch (IOException e) {
             System.err.println(e);
         }finally{
             if(out != null){
                 out.close();
             }
         } 

所以最后,我希望它写入一个已经存在的 XML 文件(我可以通过简单地更改写入器的位置来做到这一点)。问题是,这个 XML 文件有一个名为 &lt;data&gt; 的根标签。我需要将程序的结果放在 XML 文件的底部,但要在 &lt;/data&gt; 之前。这是唯一的要求。我发现的一切似乎都太复杂了,我无法弄清楚..

非常感谢任何帮助!

【问题讨论】:

    标签: java xml xml-parsing printwriter bufferedwriter


    【解决方案1】:

    您应该使用体面的 XML API。例如,这里有一个使用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);
            }
        }
    }
    

    真的没那么难......而且它会比手动写出来要强大得多。 (例如,如果您的事件标题包含“&”,这将做正确的事情 - 而您的代码会产生无效的 XML。)

    【讨论】:

    • 如何使用 JDOM 在 XML 文档中添加注释?
    • @MariuszS:我不知道,所以我查看了文档。我没花很长时间,我相信你也不会花很长时间 :)
    • 嗨 Jon,我实际上正在编写一个程序来更新 SIMILIE Timeline Creator 的 XML 文件。创建者不使用任何 XML 标记,除了 ,因此设置这些元素我认为不适合我。
    • @user2221125:我不明白你的意思。我的示例代码只添加了event 标签。你认为我给出的代码不能使用什么?
    • @Mariusz@ 我已经找到了解决方案,但非常感谢您的帮助!
    【解决方案2】:

    如果你喜欢fluent api,那么你可以使用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);
    

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

    【讨论】:

    • 这对我没有帮助,因为我不想创建 XML 文件。 XML 文件是预先存在的,我需要在它后面附加从我的 GUI 程序输入的信息。
    • 你太快了 :) 这还没有完成 :D
    • 我不认为 StringReader 做你认为它做的事情。
    【解决方案3】:

    您可以使用JOOX。这就是你将如何做一个追加:

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = factory.newDocumentBuilder();
    Document doc = parser.parse("/pathToXML");
    
    JOOX.$(doc).append("<newNode>data<newNode>");
    

    默认情况下 $(doc) 将加载根节点。如果你想要一个内部节点,你可以使用 find() 方法。该库的文档记录不是很好,但作为开源,您可以随时直接查看源代码。

    【讨论】:

    • 您可以使用如下代码创建文档:$(new File("/pathToXML")).document();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    相关资源
    最近更新 更多