Get XML of CI using script

Jose Santos Alv
Tera Contributor

Instead of clicking export -> XML (This record) .How can I easily get/export the XML of a CI using script and then this file, attach it into sys_attachment table ?

 

 

 

3 REPLIES 3

Sai Shravan
Mega Sage

Hello @Jose Santos Alv ,

 

Below is a script that retrieves the XML representation of a Configuration Item (CI), saves it as an attachment, and attaches it to the specified record:

 

 

 

// Specify the table name and CI sys_id
var tableName = 'cmdb_ci';
var ciSysId = 'YOUR_CI_SYS_ID_HERE';

// Retrieve the XML representation of the CI
var ciGR = new GlideRecord(tableName);
if (ciGR.get(ciSysId)) {
    var xmlString = new XMLSerializer().serializeToString(ciGR);
    
    // Create a new attachment record
    var attachmentGR = new GlideRecord('sys_attachment');
    attachmentGR.initialize();
    attachmentGR.file_name = 'CI_' + ciGR.getValue('name') + '.xml'; // Specify the file name
    attachmentGR.table_name = tableName;
    attachmentGR.table_sys_id = ciSysId;
    attachmentGR.content_type = 'application/xml';
    attachmentGR.type = 'file';
    attachmentGR.file = xmlString;
    
    // Insert the attachment record
    var attachmentSysId = attachmentGR.insert();
    
    gs.info('Attachment created with sys_id: ' + attachmentSysId);
} else {
    gs.error('CI record not found.');
}

 

 

 

Replace 'YOUR_CI_SYS_ID_HERE' with the sys_id of the CI you want to export. This script will retrieve the XML representation of the CI, create a new attachment record, and attach the XML file to the CI record.

Make sure to test this script in a non-production environment before using it in a production instance. Also, ensure that the appropriate permissions are set to create attachments and access the CI records.

 

Please mark this as helpful and correct answer, if this helps you

 

Regards,
Shravan
Please mark this as helpful and correct answer, if this helps you

Hello Sai, thanks a lot for your response. While testing your code I got this error : "

XMLSerializer" is not defined.  

Do I need something else ? 

garyminnick
Tera Contributor

I had the same issue and I searched on that line and found this article.

How does serialize() method of GlideRecordXMLSeria... - ServiceNow Community

 

which led me to this function

var xmlString = new GlideRecordXMLSerializer().serialize(ciGR);

 

xmlString now contains the xml data of the ci.  However, it does escape the quotes so it is not 100%.  There maybe another method for that function but I was not able to find that function.