从Java写入XML文档 – 简单

我知道在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文件一个标记,称为< data>.我需要将我的程序的结果放在XML文件底部,但是请来BEFORE< / data>.这是唯一的要求.我发现的一切看起来都太复杂了,我无法弄明白……

很感谢任何形式的帮助!

解决方法

您应该使用一个不错的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.)

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...