[英]add child nodes using libxmljs (Node.js) to a XML file
I'm trying to add a new child node to an xml file; 我正在尝试将新的子节点添加到xml文件中; 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(). 您的问题是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.
您需要的是xmlDoc.root()返回当前的根节点。 There are other things wrong with this code sample though.
但是,此代码示例还有其他问题。 See documentation https://github.com/polotek/libxmljs/wiki
参见文档https://github.com/polotek/libxmljs/wiki
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.