2012-07-31 79 views
1

我想知道是否有人可以帮助将数据附加到XML文件。下面,我有代码从其他XML文件抓取数据,做一些逻辑更改,并将更改写入新的输出文件。然而,看这api如何使用jdom和java将数据追加到xml文件中

m having trouble understanding which method does appending. It seems like all of them creates a new XML file doc/overwrites an existing one if it exists. I m试图追加标签到新文件,因为我循环。

 for(int i = 0; i < itemList.size(); i++){ 

      //get the specific item node 
      Element item = (Element)itemList.get(i); 

      //there are some non item nodes so need this check 
      if(item.getName().equals("item")){ 

       //do some logic changing to the tags 

       //System.out.println(item.getValue()); 
       //System.out.println(item.getChild("Q").getValue()); 
       //System.out.println(item.getChild("A").getValue()); 

       boolean exists = (new File("/Users/davidyu/Desktop/file2.xml")).exists(); 
       //if file exists 
       if(exists){ 
        System.out.println("in here1"); 
        xmlOutput.????? 
       } 
       else{ 
        System.out.println("in here2"); 
        xmlOutput.output(doc, new FileWriter("/Users/davidyu/Desktop/file2.xml")); 
       } 

      } 

我基本上试图做的是在每次循环迭代后为文件写一个新的item标签。该项目标签应包含新的childNodes“Q”和“A”。

我该怎么做?

回答

2

鉴于您正在循环执行此操作,因此在循环开始之前加载文件一次,然后遍历循环并随时向文档中添加元素,然后保存它在循环之后再次。如果文件事先不存在,请创建一个新的文档(只在内存中,稍后保存),并使用您需要的任何结构 - 例如只是一个适当的根元素。当然,您需要确定要添加新元素的位置。

没有简单的方法将元素添加到现有的XML文件没有首先加载现有的文件。 (虽然你可能可能以流方式进行,但编码可能会复杂得多。)

0

XMLOutputter只是将一个现有的XML结构输出到一个目的地 - 在你的情况下是一个文件。在我看来,您有兴趣改变现有XML文档的结构。如果是这样的话,那么一旦你必须要要(在你的例子Element item = (Element)itemList.get(i);)将内容添加到元素的引用,你需要做的是这样的:

Element newElement = new Element("NewElement"); 
item.addContent(newElement); 

这将添加的元素<NewElement/>item元素给

<item> 
    <NewElement/> 
</item> 

下见Element的javadoc。