Home > front end >  Generate XML using server side suiteScript 2.0
Generate XML using server side suiteScript 2.0

Time:05-13

I am trying to use suitescript on a 2.0 Suitelet script to generate xml and then I would like to return the Xml as a string. Please note, that I have to build this XML on the fly so I can't just read it from a file. On a client script I can use native javascript and build around the document but in the server side I assume I have to use the N/XML module and leverage Document, Element, and Node to build this.
An example of the XML I would like to return as a string might be generated as the following:

As a side note, I was hoping I would not do this directly as a string but rather work with the xml logic by not just building a long string and parsing that string to XML.

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

In the end I want to return string:

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

As I said I assume since its a server side suitescript I would use N/xml and its document,node,parser, etc. members..

the code I have is as follows:

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})

But the line that does the appendChild gives me an error "HierarchyRequestError: Failed to execute 'appendChild' on 'Node': Only one element on document allowed.: null"

CodePudding user response:

indeed. You can use N/xml as follows:


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});


});
  • Related