Insert node as first child always
I have a basic XML document setup like this:
<rss>
<channel>
</channel>
</rss>
I would like to add new child nodes of the channel as the first node, so, say I'm looping through a collection of items, then the first item would be added like this:
<rss>
<channel>
<item>Item 1</item>
</channel>
</rss>
Then the next item would added like this:
<rss>
<channel>
<item>Item 2</item>
<item>Item 1</item>
</channel>
</rss>
I've been trying to use:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.n开发者_如何学JAVAewInstance();
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);
But it keeps adding new items to the bottom of the list.
channelNode.appendChild(itemNode);
will always append the itemNode
to the end of the list of children of channelNode
. This is behavior is defined in the DOM Level 3 specification, and in the JAXP documentation as well:
Node appendChild(Node newChild) throws 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.
If you need to add at the beginning of the list of child nodes, you can use the insertBefore()
API method instead:
channelNode.insertBefore(itemNode, channelNode.getFirstChild());
精彩评论