簡體   English   中英

使用服務器端 suiteScript 2.0 生成 XML

[英]Generate XML using server side suiteScript 2.0

我正在嘗試在 2.0 Suitelet 腳本上使用 suitescript 來生成 xml,然后我想將 Xml 作為字符串返回。 請注意,我必須即時構建這個 XML,所以我不能只從文件中讀取它。 在客戶端腳本上,我可以使用本機 javascript 並圍繞文檔進行構建,但在服務器端,我假設我必須使用 N/XML 模塊並利用 Document、Element 和 Node 來構建它。
我想以字符串形式返回的 XML 示例可能會生成如下:

作為旁注,我希望我不會直接作為字符串執行此操作,而是通過構建一個長字符串並將該字符串解析為 XML 來使用 xml 邏輯。

<shipment>
    <book>
        <title>aaa</title>
        <author>bbb</author>            
    </book>
</shipment>

最后我想返回字符串:

"<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: Failed to execute 'appendChild' on 'Node': Only one element on document allowed.: 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});


});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM