How to create script to export list of records in xml and create attachments
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-29-2023 10:18 AM
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.');
}
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-03-2024 06:48 AM
Hello Ankur. That's actually crossed my mind, and I am considering it. Thanks for the suggestion.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-05-2024 10:17 AM
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