始终将节点插入第一个子节点

时间:2011-08-03 02:07:19

标签: java xml

我有一个基本的XML文档设置:

 <rss>
      <channel>
      </channel>
 </rss>

我想将频道的新子节点添加为第一个节点,因此,假设我循环遍历一组项目,那么第一个项目将添加如下:

 <rss>
      <channel>
           <item>Item 1</item>
      </channel>
 </rss>

然后下一个项目将添加如下:

 <rss>
      <channel>
           <item>Item 2</item>
           <item>Item 1</item>
      </channel>
 </rss>

我一直在尝试使用:

 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
 DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
 Document doc = docBuilder.parse(new File(xmlFile));

 Element itemNode = doc.createElement("item");
 Node channelNode = doc.getElementsByTagName("channel").item(0);
 channelNode.appendChild(itemNode);

但它不断在列表底​​部添加新项目。

1 个答案:

答案 0 :(得分:3)

channelNode.appendChild(itemNode);

将始终将itemNode附加到channelNode子项列表的末尾。这种行为在DOM Level 3规范中定义,在the JAXP documentation中定义:

  

节点 appendChild (节点newChild)                    抛出DOMException

    Adds the node newChild to the end of the list of children of this
node (emphasis mine). If the newChild is already in the tree, it is first removed.

如果您需要在子节点列表的开头添加,则可以改为使用insertBefore() API方法:

channelNode.insertBefore(itemNode, channelNode.getFirstChild());
相关问题