I'm trying to add a new child node to an xml file; so far I have this code:
var libxml = require('libxmljs');
var xml = '<?xml version="1.0" encoding="UTF-8"?>' +
'<root>' +
'<child foo="bar">' +
'<grandchild baz="fizbuzz"><blah>grandchild content</blah></grandchild>' +
'</child>' +
'<child foo="bar1">' +
'<grandchild baz="fizbuzz">grandchild content 1</grandchild>' +
'</child>' +
'<child foo="bar3">' +
'<grandchild baz="fizbuzz3">grandchild content 3</grandchild>' +
'</child>' +
'<sibling>with content!</sibling>' +
'</root>';
var xmlDoc = libxml.parseXml(xml);
var allxml = xmlDoc.root(); //store all nodes as allxml
var allNodes = xmlDoc.childNodes(); //all child nodes to array
var elem = xmlDoc.node('name1');
var newChild = libxml.Element(xmlDoc, 'new-child');
elem.addChild(newChild);
But I get the following error when I run this:
return this._root(elem);
^
Error: Holder document already has a root node
Does anyone know whats going on here?
Your problem is xmlDoc.node(). On the document, this method tries to create a new root node. What you want is xmlDoc.root() to return the current root node. There are other things wrong with this code sample though. See documentation https://github.com/polotek/libxmljs/wiki