我试图使用2.0套件脚本生成xml,然后我想返回xml作为字符串。请注意,我必须动态地构建这个XML,所以不能直接从文件中读取它。在客户端脚本上,我可以使用原生javascript并围绕文档进行构建,但在服务器端,我假设我必须使用N/XML模块并利用document、Element和Node来构建它。
我希望作为字符串返回的XML示例可能如下所示:
作为旁注,我希望我不会直接作为字符串这样做,而是通过不只是构建一个长字符串并将该字符串解析为xml来处理xml逻辑。
<shipment>
<book>
<title>aaa</title>
<author>bbb</author>
</book>
</shipment>
最后我想返回string:
"<shipment><book><title>aaa</title><author>bbb></author></book></shipment>"
正如我所说,我假设因为它是一个服务器端套件脚本,我将使用N/xml及其文档,节点,解析器等成员。
的代码如下:
require(["N/xml"]);
var x= require("N/xml");
var xmlDocument = x.Parser.fromString({
text: '<shipment/>'
});
var newBookNode = xmlDocument.createElement("book");
var newTitleNode = xmlDocument.createElement("title");
var newTitleNodeValue = xmlDocument.createTextNode("aaa");
var newAuthorNode = xmlDocument.createElement("author");
var newAuthorNodeValue = xmlDocument.createTextNode("bbbb");
newBookNode.appendChild(newTitleNode);
newBookNode.appendChild(newAuthorNode);
newTitleNode.appendChild(newTitleNodeValue);
newAuthorNode.appendChild(newAuthorNodeValue);
xmlDocument.appendChild(newBookNode)
var asString2 = x.Parser.toString({document:doc1})
但是做appendChild的行给了我一个错误"HierarchyRequestError:未能在'Node'上执行'appendChild':只允许文档上的一个元素。: null"
确实如此。你可以这样使用N/xml:
require(['N/xml'...], function(xml,...){
var doc = xml.Parser.fromString({
text:'<cXML payloadID="'+ payLoadId +'"></cXML>'
});
doc.documentElement.appendChild({newChild:doc.createElement({tagName:'Lab'})});
var asString = xml.Parser.toString({document:doc});
});