We're reclaiming inactive PDIs to keep them available for active builders. Learn what's changing, who's affected, and how to protect your work. Read More

How to create script to export list of records in xml and create attachments

khogan
Tera Contributor

I need a script to back up several tables, all records/fields including sysid as an xml and attach to a catalog request, or at the least get it created in the sys_attachment, and I should be able to link the request to the attachments from there.  There should be an attachment for each table listed.

 

@Riya Verma  Riya's solution, in this post is very close to what I need but I am a scripting novice and can't seem to modify it to my needs. Solved: Re: Use Script to export records to XML - ServiceNow Community

 

// Define the tables you want to export records from
var tablesToExport = ['em_match_rule', 'em_mapping_pair', 'em_compose_field', 'em_match_field', 'em_mapping_rule'];

// Loop through each table
for (var i = 0; i < tablesToExport.length; i++) {
var tableName = tablesToExport[i];

// Query records from the table
var gr = new GlideRecord(tableName);
gr.query();

// Create XML document
var xmlDoc = new XMLDocument();
xmlDoc.createElement(tableName + 's'); // Root element

// Loop through the records
while (gr.next()) {
var recordNode = xmlDoc.createElement(tableName);

// Add fields as child elements
var fields = gr.getFields();
for (var j = 0; j < fields.size(); j++) {
var field = fields.get(j);
var fieldName = field.getName();
var fieldValue = gr.getValue(fieldName);

var fieldNode = xmlDoc.createElement(fieldName);
fieldNode.setTextContent(fieldValue);
recordNode.appendChild(fieldNode);
}

xmlDoc.appendChild(recordNode);
}

// Export XML to a file
var xmlContent = xmlDoc.toString();

// Save the xmlContent to a file using appropriate methods for your environment. This is the part I cannot figure out.

// Log the export details
gs.info('Exported ' + gr.getRowCount() + ' records from ' + tableName + ' to XML.');
}

 

 

 

12 REPLIES 12

Hello Ankur. That's actually crossed my mind, and I am considering it. Thanks for the suggestion.

talent
Tera Contributor

I used the oob export, but instead of pulling the xml records from the mid server, back into servicenow, I used the sys_attachment records it created and updated the table_sysid and tablename fields with the request's sysid and tablename. It now attaches the xml recocords to the request. Thanks everyone for the help

Christopher Wea
Tera Contributor

Okay - so a working example of how to do this - it outputs in JSON rather than XML.
It hangs records off the current sys_user.

var exports = {
    'sys_choice' : 'name=u_request^element=state'
};

Object.keys(exports).forEach ( function (_tableName) {
    var exportRecords = [];
    var  exportGlideRecords = new GlideRecord(_tableName);
    var jobName = _tableName +'_' + exports[_tableName];
    exportGlideRecords.addEncodedQuery(exports[_tableName]);

    exportGlideRecords.query();

    while(exportGlideRecords.next()) {
       exportRecords.push( glideRecordToObject(exportGlideRecords) );
    }

    var storeID = storeObjectsAsAttachments(exportRecords, jobName+'.json');

    gs.info(jobName + '----|'+'\\sys_attachment?sys_id='+storeID);

});

function glideRecordToObject (_glideRec, _addDisplayValues, _embedFields) {
    var hashObj = {};
    var gRU = new GlideRecordUtil();
   
    gRU.populateFromGR(hashObj, _glideRec);

    var fields = gRU.getFields(_glideRec);
    for (var i = 0; i < fields.length; i++) {
        var field = fields[i];
        if (!(field in hashObj)) {
            hashObj[field] = null;
        }
        if (_addDisplayValues) {
            var displayValue = String(_glideRec.getDisplayValue(field));
            if (displayValue.length > 0 && displayValue != 'null') {
                hashObj[field + 'Display'] = displayValue;
            }
        }
    }

    if (_embedFields  && _embedFields.length > 0) {
        for (var embedField in _embedFields ) {
            if (_embedFields.hasOwnProperty(embedField)) {
                hashObj[embedField] = _embedFields[embedField];
            }
        }
    }

    gs.info('Converted GlideRecord with sys_id: ' + _glideRec.getValue('sys_id') + ' to object: ' + JSON.stringify(hashObj));

    return hashObj;
};

function storeObjectsAsAttachments (_hashObjs, _filename) {
    var jsonStr = JSON.stringify(_hashObjs);
    //Hang attachments off the current user, but it can be anything
    var tableName = 'sys_user';
    var recordSysId = gs.getUser().getID();

    var tableRec = new GlideRecord('sys_user');
    tableRec.get(recordSysId);
    var fileName = _filename;
    var contentType = 'text/json';
    var fileContent = jsonStr;

    // Initialize GlideSysAttachment and write the file
    var gsa = new GlideSysAttachment();
    var attachmentId = gsa.write(tableRec, fileName, contentType, fileContent);

    return attachmentId;

}