Get XML of CI using script
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-01-2024 03:04 PM
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 ?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-03-2024 03:37 AM
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
Shravan
Please mark this as helpful and correct answer, if this helps you
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-06-2024 06:26 AM
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 ?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-13-2025 08:46 AM
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.