【问题标题】:how to append data to an xml file using jdom and java如何使用 jdom 和 java 将数据附加到 xml 文件
【发布时间】:2012-07-31 15:33:40
【问题描述】:

我想知道是否有人可以帮助将数据附加到 XML 文件中。下面,我有代码,它从另一个 xml 文件中获取数据,进行一些逻辑更改,并将更改写入新的输出文件。然而,通过这个api

Im 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. Im 在循环时尝试将标签附加到新文件。

        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"));
                }

            }

我基本上想要做的是在每次循环迭代后将一个新的项目标签写入文件中。该项目标签应包含新的子节点“Q”和“A”。

我该怎么做?

【问题讨论】:

    标签: java xml jdom


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      XMLOutputter 只是将现有的 XML 结构输出到目标 - 在您的情况下是文件。在我看来,您似乎对更改现有 XML 文档的结构感兴趣。如果是这种情况,那么一旦您引用了要添加内容的元素(在您的示例中为 Element item = (Element)itemList.get(i);),您需要执行以下操作:

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

      这将在item元素下添加元素&lt;NewElement/&gt;

      <item>
           <NewElement/>
      </item>
      

      请参阅Element javadocs。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-25
        • 2023-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-09
        相关资源
        最近更新 更多