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.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);
But it keeps adding new items to the bottom of the list.
will always append the
itemNodeto the end of the list of children ofchannelNode. This is behavior is defined in the DOM Level 3 specification, and in the JAXP documentation as well:If you need to add at the beginning of the list of child nodes, you can use the
insertBefore()API method instead: