Вы находитесь на странице: 1из 114

ServiceCenter 6.

x JavaScript Programming Guide


Using JavaScript in ServiceCenter 6.x Tailoring Tools
HP OpenView IT Service Management

Introduction ......................................................................................................................................................4 Requirements ..............................................................................................................................................4 How to use this document............................................................................................................................4 Introduction to JavaScript in ServiceCenter .....................................................................................................4 Language overview......................................................................................................................................4 Basic rules of JavaScript..............................................................................................................................5 Structure of a JavaScript application .......................................................................................................5 Expressions and operators ......................................................................................................................5 JavaScript objects and properties............................................................................................................5 Built-in objects and functions ...................................................................................................................6 Conditional statements ............................................................................................................................6 While and loop statements.......................................................................................................................6 Break and continue statements ...............................................................................................................7 Use of JavaScript in ServiceCenter .................................................................................................................7 Order of execution of JavaScript versus RAD language ..............................................................................8 The ScriptLibrary .........................................................................................................................................9 Using the ScriptLibrary.............................................................................................................................9 Corresponding JavaScript syntax for RAD language tasks........................................................................10 JavaScript global properties.......................................................................................................................11 Query operators.....................................................................................................................................11 JavaScript return code properties ..........................................................................................................11 Examples of calling JavaScript from different ServiceCenter tools ............................................................12 FormatControl........................................................................................................................................12 Triggers..................................................................................................................................................13 Links ......................................................................................................................................................14 Programmers reference ................................................................................................................................15 JavaScript global system objects...............................................................................................................16 system.files ............................................................................................................................................16 system.forms .........................................................................................................................................16 system.functions ....................................................................................................................................17 system.library.........................................................................................................................................17 system.oldrecord ...................................................................................................................................18 system.record ........................................................................................................................................18 system.sysinfo .......................................................................................................................................18 system.threads ......................................................................................................................................18 system.user ...........................................................................................................................................19 system.users..........................................................................................................................................19 system.vars............................................................................................................................................19 JavaScript global methods.........................................................................................................................20 print........................................................................................................................................................20 readFile..................................................................................................................................................20

writeFile .................................................................................................................................................21 Quit ........................................................................................................................................................21 base64Encode.......................................................................................................................................22 base64Decode.......................................................................................................................................22 xmlstring ................................................................................................................................................23 doHTTPRequest ....................................................................................................................................23 doSOAPRequest ...................................................................................................................................24 makeSCWebURL ..................................................................................................................................25 help ........................................................................................................................................................26 RCtoString .............................................................................................................................................26 execute ..................................................................................................................................................27 compile ..................................................................................................................................................27 JavaScript objects......................................................................................................................................28 Attachment.............................................................................................................................................28 Header ...................................................................................................................................................28 Datum ....................................................................................................................................................29 SCDatum ...............................................................................................................................................30 SCFile ....................................................................................................................................................31 XML .......................................................................................................................................................33 XMLDate................................................................................................................................................34 JavaScript methods for the SCFile, SCDatum, and Datum objects ...........................................................36 SCFile.doAction()...................................................................................................................................36 SCFile.doDelete() ..................................................................................................................................37 SCFile.doInsert()....................................................................................................................................38 SCFile.doRemove() ...............................................................................................................................39 SCFile.doSave() ....................................................................................................................................39 SCFile.doSelect(query) .......................................................................................................................40 SCFile.doUpdate() .................................................................................................................................41 SCFile.getFirst().....................................................................................................................................42 SCFile.getLast().....................................................................................................................................43 SCFile.getNext() ....................................................................................................................................44 SCFile.getPrev() ....................................................................................................................................44 SCFile.getSize().....................................................................................................................................45 SCFile.getText().....................................................................................................................................46 SCFile.getType()....................................................................................................................................47 SCFile.getXML() ....................................................................................................................................48 SCFile.isRecord() ..................................................................................................................................49 SCFile.join() ...........................................................................................................................................50 SCFile.JSDate(dataType) ......................................................................................................................50 SCFile.length() .......................................................................................................................................51 SCFile.pop()...........................................................................................................................................53 SCFile.push(arrayItem)..........................................................................................................................53 SCFile.setType(dataType) .....................................................................................................................54 SCFile.setValue(newValue) ...................................................................................................................55 SCFile.shift() ..........................................................................................................................................56 SCFile.toArray() .....................................................................................................................................57 SCFile.unshift(arrayItem) .......................................................................................................................58 JavaScript methods for the XML object .....................................................................................................59 XML.addAttribute(AttributeName, AttributeValue) .................................................................................59 XML.addElement(String)........................................................................................................................60 XML.appendNode(name).......................................................................................................................62 XML.createNode(type, name, value) .....................................................................................................63 XML.getAttributeNode(Attribute)............................................................................................................64 XML.getAttributeValue(Attribute) ...........................................................................................................66 XML.getDocumentElement()..................................................................................................................67 XML.getFirstAttribute(Element)..............................................................................................................68 XML.getFirstChildElement(Element)......................................................................................................71 XML.getName() .....................................................................................................................................73 XML.getNextAttribute(Element) .............................................................................................................74 XML.getNextSiblingElement(Element)...................................................................................................76 XML.getNodeName() .............................................................................................................................79 XML.getNodeType() ..............................................................................................................................80 XML.getNodeValue() .............................................................................................................................81 XML.getParentNode(Element)...............................................................................................................82 XML.getPrefix()......................................................................................................................................85

XML.getQualifiedName() .......................................................................................................................87 XML.getText() ........................................................................................................................................89 XML.getValue()......................................................................................................................................90 XML.importNode(name).........................................................................................................................92 XML.isDocumentElement() ....................................................................................................................93 XML.setAttributeValue(AttributeName, AttributeValue) .........................................................................95 XML.setContent(String) or XML.setContent("FilePath", IsFile) ..............................................................97 XML.setNodeValue(String) ....................................................................................................................99 XML.setText(String) ............................................................................................................................. 100 XML.setValue(String)........................................................................................................................... 101 XML.toXMLString() .............................................................................................................................. 103 JavaScript methods for the XMLDate object............................................................................................ 103 XMLDate.addDuration(duration) .......................................................................................................... 103 XMLDate.getDate() .............................................................................................................................. 104 XMLDate.getDatum() ........................................................................................................................... 104 XMLDate.getGMTSCDateTimeString()................................................................................................ 104 XMLDate.getISODate()........................................................................................................................ 105 XMLDate.getISODateTimeString() ...................................................................................................... 105 XMLDate.getISODay() ......................................................................................................................... 105 XMLDate.getISOMonth() ..................................................................................................................... 105 XMLDate.getISOTime() ....................................................................................................................... 106 XMLDate.getISOYear()........................................................................................................................ 106 XMLDate.getSCDateTimeString()........................................................................................................ 106 XMLDate.JSDate()............................................................................................................................... 107 XMLDate.toSCDuration(duration) ........................................................................................................ 107 Cross-reference: Index of methods and functions by task .......................................................................... 108 Array handling.......................................................................................................................................... 108 Date/Time handling.................................................................................................................................. 109 Database or file manipulation .................................................................................................................. 110 Basic functionality .................................................................................................................................... 110 Conversions............................................................................................................................................. 111 XML ......................................................................................................................................................... 111 For more information.................................................................................................................................... 114

Introduction
With the release of ServiceCenter 6.0, system administrators can now use the standard JavaScript scripting language to customize their ServiceCenter applications. JavaScript is a widely supported, industry-standard programming language that eliminates the need for a separate programming skill set, and reduces user reliance on proprietary tools. The introduction of JavaScript into ServiceCenter does not invalidate the current ServiceCenter RAD tool set; instead, the JavaScript interface is an alternative to the RAD language for tailoring.

Requirements
This document is targeted for ServiceCenter system administrators and assumes that the reader is familiar with object-oriented programming and JavaScript development. It provides an overview of JavaScript functionality in ServiceCenter, using both examples and descriptions of JavaScript's objects, properties, methods, and functions.

How to use this document


This document is divided into three sections: The section Introduction to JavaScript in ServiceCenter introduces basic rules of JavaScript and describes its use in ServiceCenter. The section Use of JavaScript in ServiceCenter describes the use of the JavaScript language as it relates to ServiceCenter customization and tailoring. It provides detailed examples to aid beginners who are developing their first JavaScript application in ServiceCenter. The Programmers reference is a complete reference for JavaScript in ServiceCenter. It includes information and key examples for all available objects, properties, and methods.

Introduction to JavaScript in ServiceCenter


Like RAD, JavaScript in ServiceCenter provides the ability to query, insert, update, and delete database records, and to make use of existing RAD variables and functions. The principal benefit of using JavaScript is that it uses an industry-standard scripting language to execute commands instead of a proprietary language. JavaScript within ServiceCenter is implemented using the Mozilla SpiderMonkey (JavaScriptC) Engine. For detailed information about the syntax of Mozilla SpiderMonkey JavaScript, refer to:
http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html

For information about the SpiderMonkey project refer to:


http://www.mozilla.org/js/spidermonkey/

Language overview
JavaScript is a scripting language which is different from programming languages like Java, C++ or Visual Basic. It is a smaller, dynamically typed scripting language that offers programming tools with easy syntax and built-in functionality. Unlike programming languages, scripting languages do not use compilers to create executable program code. Because JavaScript is an interpreted language, each time the script is executed, it is loaded into an interpreter that runs the code. The Compile button in the Script Library does not create an executable load module; it runs a syntax check to verify that the script is executable. JavaScript can be either client-side, server-side, or core language. Core JavaScript is the base JavaScript language with client-side and server-side JavaScript as extensions. Server-side JavaScript is used for accessing and manipulating data, and is the only one available within ServiceCenter.

Basic rules of JavaScript


The following rules apply to the basic syntax of JavaScript: JavaScript is case-sensitive. Statements should end in a semicolon (;). Variables Must be defined before being used. The variable name can contain A Z, a z, underscore or digits and must start with a letter or an underscore (_). Assume the type of the data that is put into the variable. The data type does not have to be explicitly defined. Are global variables when defined outside of a function, and are available anywhere in the current application. Variables created within a function are local variables, and can be used only within that function.

Strings have to be enclosed in quotation marks, either a single or double. For example: print(Hello + world + Country.name) produces the following: Hello world US. Special characters that are displayed literally must be preceded by a backslash character (\). Quotes within a string can be entered preceded by a backslash as well. See
http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html

Part 2, Item 6, "String literals" section for more information. To increment a variable, such as a = a + 1, you can use a++. You can decrement a variable in the same way, as in a--. To enter comments in the script, use "//" to start a single line comment or the combination of "/*" and "*/" to enclose a multi-line comment. Values that are not defined as a data type (string, number, Boolean) may be defined as an object, such as Date, Array, Boolean, String, and Number. As an example you could define: var ArrayList=new Array(test, this, list); Dots in ServiceCenter field names must be replaced by an underscore (_) in JavaScript. For example contact.name becomes contact_name. ServiceCenter field names that are reserved words in JavaScript have to be preceded by an underscore, such as _class for the class field.

Structure of a JavaScript application


<Global variable declarations;> function <function name>(<parameters>) { <local variable declarations;> <Statements;> } <function calls;>

Expressions and operators


For more information on this topic refer to:
http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html

See Part 2, Item 7, "Expressions and Operators" section. The list of operators includes assignment operators, comparison operators, arithmetic operators, bitwise operators, logical operators, string operators, and special operators.

JavaScript objects and properties


The key to understanding JavaScript is learning the structure of its objects. JavaScript is an objectoriented language with many similarities to the C programming language. Most JavaScript functionality is contained in objects. The objects contain methods, parameters, and events. Each object may contain a set of properties that more closely define the object. JavaScript objects do not have normal class-to-subclass relationships: Subclasses are contained within classes but do not

inherit their properties. The syntax you use to call methods and properties is: Object.method or Object.property. For more information on JavaScript objects and properties refer to:
http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html

See Part 2, Item 8, "Object model" section.

Built-in objects and functions


Built-in objects described in this section are Array, Boolean, Date, Function, Math, Number, and String. Each of these is described in detail at:
http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html

See Part 2, Item 9, the "Built-in objects and functions" section.

Conditional statements
The following example returns true if the date entered is within the number of days in a month (here, 30 days); otherwise, it returns false. Note the use of the conditional statement to shorten the "if" expressions. The statement: var return = (parm.Date.getDate <= 30) ? true : false; Works in the same way as its much longer equivalent: var return=false; if (parm.Date.getDate <= 30) { return = true; } Else { return=false; }

While and loop statements


Note: Whenever programming a loop statement, ensure that the exit condition will be met; otherwise an infinite loop will occur. For detailed information about the for and while loop statements, refer to
http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/index.html

See Part 2, Item 10, "Overview of JavaScript statements," in the Loop statements section. The following example shows how to check how many times a given number can be divided by 2, first using a "for" loop, and then using a "while" loop: function DividableByTwoFOR(ParmNumber) { for (var i=0; ParmNumber > 1; i++) { ParmNumber = ParmNumber / 2; } return i; } fuction DividableByTwoWHILE(parmNumber) { var i = 0; while( ParmNumber > 1 ) {

ParmNumber = ParmNumber / 2; i++; } return i; } Note: A Do..While loop is available for those instances when you want to execute a statement (or block of statements) at least once. In a Do..While loop the exit condition is checked after the statements are executed.

Break and continue statements


The break statement terminates a "while" or "for" loop completely. The continue statement terminates execution of the statements within a "while" or "for" loop and continues the loop in the next iteration. The following two examples demonstrate how these statements are used. Note: Both these statements violate the rules of structured programming, but are nonetheless widely used in special cases. function { var i var n while { if { break4error(parmArray, x) = 0; = 0; (i < 10) (isNaN(parmArray[x])) print(parmArray[i].toString + is not numeric. Please repair and run again; break; } n = n + parmArray[i]; i++; } return n; } Modifying the above example, the continue statement would work as follows: function { var i var n while { if { break4error(parmArray, x) = 0; = 0; (i < 10) (isNaN(parmArray[x])) print(parmArray[i].toString + is not numeric. Continuing with next number; i++; continue; } n = n + parmArray[i]; i++; } return n; }

Use of JavaScript in ServiceCenter


You can use JavaScript in the previously discussed tailoring tools in ServiceCenter 6.x and higher. In addition to these areas where JavaScript can be entered directly, the functions entered in the ScriptLibrary can be accessed from anywhere in ServiceCenter where expressions are evaluated, such as on a RAD process panel.

Order of execution of JavaScript versus RAD language


This section lists all tailoring tools in which JavaScript can be directly entered and describes at what point in the process the JavaScript code will be executed. FormatControl The JavaScript is executed after calculations and before validations. JavaScript code in FormatControl is executed via the format.cjavascript RAD. Links JavaScript in links is executed after the (initial) expressions, but before the fill or find is executed. This is done in us.link on evaluate.expressions. The post JavaScript is executed after the fill or find was performed, immediately after the post expressions. This happens in us.fill or us.find, respectively, on the eval.post.expressions panel. Triggers The JavaScript in the triggers file is executed after the RAD application. This is controlled by the server binaries, and not by RAD code. Cascade updates The JavaScript in cascade updates is executed from the RAD application process.update.config.record. The evaluate expressions panel is executed before the evaluate.javascript panel, so that expressions take precedence over JavaScript. Scripts In script.execute on panel exec.statements, RAD expressions are processed before JavaScript expressions. Wizards Wizards use JavaScript in 3 different areas: During File Selection, Actions, and Cancel Expressions. File Selection: The Select $L.file by information is processed first, followed by the Initial Expressions and the JavaScript. Actions: In the Actions tab, the Expressions are run first, then the JavaScript, followed by the information on the Format Control / Process Name tab. Cancel Expressions: Here first the Expressions Executed on Cancel are processed, followed by Javascript Executed on Cancel. Interoperability (ioaction file) The ioaction file executes only JavaScript, and not RAD, expressions. The JavaScript code is executed in the ioevents.process.action application on the panel process.action. Display screens In the display application on the panel prep.screen, the JavaScript expressions are executed after the RAD expressions. Display options Display options have pre- and post-JavaScript and RAD expressions that are executed in the following order:
1. 2. 3. 4. 5. 6.

Pre-RAD expression Pre-JavaScript RAD application Post-RAD expression Post-JavaScript Display Action

Processes Process records have initial and final JavaScript and RAD expressions that are executed in the following order:
1. 2. 3. 4. 5. 6. 7. 8.

Initial RAD expression Initial JavaScript Pre-RAD expressions RAD application(s) Post-RAD expressions Final RAD expression Final JavaScript Next Process (if applicable)

Schedule JavaScript in the schedule record is executed after the RAD application is called, and before the check for deleting or rescheduling the schedule record.

The ScriptLibrary
The ScriptLibrary is a file within ServiceCenter used to create, edit, compile, test, and store scripts and functions that can be called and executed from anywhere within ServiceCenter. Some of these stored JavaScript programs can be used to interface with 3rd party Web Services providers, such as real-time currency conversions. All of these JavaScripts are identified as SOAP packages within the ScriptLibrary. The integration of the Get-Answers product is performed through JavaScript stored in the Script Library as well. Note: Do not use Adminstrative Mode when entering the ScriptLibrary, since functions such as compile and execute are not available in that mode.

Using the ScriptLibrary


The Script Library has several sections. The name of the record is used to call the JavaScript via either system.library.<scriptname>.<functionname>, or via jscall(). The package field is used to group records for easier maintenance. The color-coded script editor is used to enter JavaScript code. The color codes that the script editor uses are: Red: Keywords Green: Objects, methods, and properties Teal: Comments Blue: Strings Black: Default color The screen displayed below shows how all these colors appear in the script editor:

When working with the ScriptLibrary, you can compile the JavaScript code to check for syntax errors. Executing the script will compile the code and then execute it. For executing the code, ensure that all input is made available. You can access any script or function in the ScriptLibrary from any tool within ServiceCenter that supports JavaScript, by using the following syntax: system.library.<scriptname>.<functionname>( parameters ) Within a ScriptLibrary record, you can call any function that is defined previously within the same record by simply typing: <functionname>( parameters ) To call JavaScript from any RAD process panel, you can use the jscall RAD function. The syntax for this function is: jscall( "script.function" , arg1 , arg2, ... , argN ) The following statements illustrate a JavaScript call to the system library, and a call to the script library via jscall(), respectively: system.library.tzfunctions.getTZforOperator(falcon); jscall(tzfunctions.getTZforOperator, falcon);

Corresponding JavaScript syntax for RAD language tasks


Most ServiceCenter tasks can be translated from RAD language to JavaScript by using the following table.
ServiceCenter task Create a file variable Select a record Update a record Add a record Delete a record Refer to a field in a file Access an element of an array RAD panel / expression rinit select rupdate radd rdelete result=fieldname in filevariable result=rownumer in arrayname in filevariable JavaScript expression new SCFile(filename) RC=ObjectName.doSelect(Query) RC=ObjectName.doUpdate() RC=ObjectName.doInsert() RC=ObjectName.doRemove() result=ObjectName.fieldname result=ObjectName.arrayname[rownumber]

10

ServiceCenter task Send a message to screen Convert a field / Object to string

RAD panel / expression call message application string()

JavaScript expression print(message) RC=ObjectName.getText()

JavaScript global properties


Global properties are predefined properties that are not part of any object. They are names representing values that are globally defined. The core JavaScript language has several global properties, such as NaN, and ServiceCenter has a number of additional global properties. There are two categories of ServiceCenter-defined global properties: Query operators JavaScript return code properties

Query operators
These operators are used solely for constructing query expressions using the Query object. Note: The Query object has been deprecated, but older JavaScript code within the ScriptLibrary still uses the object.
Query operator EQ LIKE NEQ GT GE LT LE ISIN Description Equals to Starts with Not equal to Greater than Greater or equal to Lower than Lower or equal to Is an element in the array

Example: var q = new Query("filename", new QueryCond("name", EQ, "ThisFile"));

JavaScript return code properties


Use these properties (which are represented internally as integer values) to test the values returned by object methods such as SCFile. To print the error message rather than the return code, use the RCtoString function.
Return code RC_ERROR RC_SUCCESS RC_CANT_HAVE RC_NO_MORE RC_DUPLICATE_KEY RC_MODIFIED Description Some other error occurred. Examine the contents of the Messages view or the sc.log file for more information. The operation succeeded. The operation failed because the resource is unavailable because some other user or process has the resource locked. No more records are available in the result set. The insert operation failed because the file already contains a record with this unique key value. The update operation failed because the record was modified by another user or process since you read it.

11

Return code RC_DELETED RC_BAD_QUERY RC_NOT_AUTHORIZED

Description The operation failed because the record was deleted by another user or process. The query failed due to incorrect query syntax. The request operation was not performed due to an authorization failure. Check the permissions associated with the user who submitted the request. The operation failed because the data supplied in a field or the record did not pass validity checks performed by the application. The operation failed. Check to make sure the file name is correct, that the file exists, and that it is not read-only. The operation failed. Check to make sure the file name is correct, that the file exists, and that it is not read-only. The operation failed. Check to make sure the file name is correct, that the file exists, and that it is not read-only. The operation failed because the file name is not valid.

RC_VALIDATION_FAILED RC_UNABLE_TO_WRITE_TO_FILE RC_UNABLE_TO_CLOSE_FILE RC_UNABLE_TO_DELETE_FILE RC_INVALID_FILENAME

Example var rc = mySCFile.doInsert(); if ( rc == RC_SUCCESS ) { print( "Insert succeeded" ); } Else throw( "Error " + RCtoString(rc) + " occurred trying to insert a record" );

Examples of calling JavaScript from different ServiceCenter tools


The following examples offer suggestions about using JavaScript in some of the tailoring tools that support this functionality. Additional JavaScript examples can be found in the Programmers reference section of this document.

FormatControl
The following example can be used to verify whether the operator who was just entered in the assignee.name field in the incident ticket is currently logged in. Otherwise, validation will fail. In the Calculations section of FormatControl, in the initial column enter a condition of true. Then add the following in the calculation column: $assignee.old = nullsub(assignee.name in $file, no assignee) Click the JavaScript tab, enter true for Add and Update, and enter the following statements: var usersXML = system.users; var usersString = usersXML.toXMLString(); var file = system.vars.$file; var newAssignee = file.assignee_name; system.vars.$IsUser=usersString.indexOf(newAssignee); In the Validation section enter the following, in the Add and Update column: assignee.name in $file~=$assignee.old; And the following expression in the Validation column: $IsUser > 0

12

Enter the following in the Validation message field: The new assignee is not logged in at this time. Please try another assignee. This example uses the standard indexOf method for the String Object, and the toXMLString() function, to search for the user who was entered as the new assignee in the XML object containing all logged-in users. Any RAD variable can be set and used by preceding it with system.vars. This lets variable values be exchanged between JavaScript and RAD expressions.

Triggers
In this example a trigger sends a message to the assignment group in an incident ticket that the ticket has been updated, and to whom it is assigned. Then it adds an activity with the information that the message has been sent. var NewRecord=system.vars.$L_new; /* This is the $L.new record passed in from the trigger */ var incNumber=NewRecord.number; var incAssignee=NewRecord.assignee_name; if (incAssignee==null) { incAssignee="no one at the moment"; } /* Insert a message schedule record into the schedule file */ function insertSchedule( incNumber, incAssignee, Adressees) { var newSchedule = new SCFile( "schedule" ); var today=new Date(); newSchedule.application= "message.bg"; newSchedule._class = "problem"; newSchedule.name= "message processor record"; newSchedule.expiration= today; newSchedule.strings[1]="1"; newSchedule.strings[2]="problem update"; newSchedule.strings[3]="Problem " + incNumber + " has been updated. It is assigned to " + incAssignee + "."; newSchedule.strings[5]="pm.main"; newSchedule.strings[6]=" Soap-Windows XP"; newSchedule.strings1=Adressees; var rc = newSchedule.doInsert(); } /* Selects the operators that are members of the assignment group to return to the calling function */ function selectAddressees(assignmentGroup) { var assignment = new SCFile( "assignment" ); var findAssignee = assignment.doSelect( " name=\""+ assignmentGroup + "\"" ); if ( findAssignee == RC_SUCCESS ) { addressList=assignment.operators; return addressList; } else { print( "Could not find assignment group. " + RCtoString( findAssignment ) ); return null; } } /* Inserts an activity with the information that the email notification to the assignment group members has been sent */ function addActivity(incNumber) {

13

var newActivity = new SCFile( "activity" ); var today=new Date(); newActivity.number= incNumber; newActivity.datestamp= today; newActivity.type= "Update"; newActivity.description[0]= "Notification email on the update has been sent to all members of the assignment group."; var result = newActivity.doAction("add"); if (result == RC_CANT_HAVE || result == 51 ) { system.library.activityUpdates.scheduleActivityUpdate ( newActivity, newActivity.type, newActivity.description ); } } /* Selects the operators to send the message to */ Addressees = selectAddressees( NewRecord.assignment ); if (Addressees != null) { /* adds the message to the schedule file for sending */ insertSchedule( incNumber, incAssignee, Addressees); /* adds an activity to inform the user of the email being sent*/ addActivity(incNumber); } The example shows (among other things) how to call a Document Engine Action; how to call a function from the Script Library; and how to insert a new record. In addition, it shows how to use several functions within a single JavaScript and how to call them. Note: Because the class field name in the schedule file is in conflict with the class keyword used in JavaScript, it must be preceded by an underscore (_).

Links
The following JavaScript code: Queries the configuration item that was previously selected from a fill. Increases a counter in that configuration item called num.issues.on.CI (this new field has to be added in the device file). Adds the new ticket number to an array of issues in the device file called array.incidents. Updates the device record. If the configuration item does not exist, it issues an error message. If the item is currently down, it sends an alert to the person who is opening the ticket. var CI_Record=new SCFile("device"); /* opens the device file */ var CIName=system.vars.$File.logical_name; /* passes in the logical name from $File */ /* Selects the configuration item to update */ function getConfigurationItem( CIName ) { var findCI_RC = CI_Record.doSelect( "logical.name=\""+ CIName + "\"" ); if (findCI_RC==RC_SUCCESS) { return CI_Record; } else { print( "Could not find configuration Item. " + RCtoString( findCI_RC ) ); return null; } } /* Increases the use counter that counts how often this item was affected by an incident ticket and enters the incident ticket number into the array of incidents */

14

function increaseUseCounter(CI) { if (CI.is_down == true) { print("The configuration item is down at the moment. Please check existing tickets if the cause for this issue is related to the down system."); } CI.num_issues_on_CI++; /* increase counter */ var incNumber = system.vars.$File.number; /* get the incident ticket number */ var array_incidents = new Array(); var ind = 0; while(CI.array_incidents[ind] != null) /* convert the SC array into a JS array (see paragraph below) */ { array_incidents[ind]=CI.array_incidents[ind]; ind++; } var j=0; var temp_string = array_incidents.toString(); var i = temp_string.indexOf(incNumber); if (i < 0) /* Check if incident is already in the list */ { /* If not, enter the incident number to the list *? if (array_incidents == null) { j=0; } else { j=array_incidents.length; } array_incidents[j] = incNumber; CI.array_incidents = array_incidents; } CI.doUpdate(); } /* Call previously defined functions to execute code */ CI=getConfigurationItem(CIName); increaseUseCounter(CI); This example shows how to query a record from within ServiceCenter, and how to update fields in that record. Additionally it shows how to transfer an array from ServiceCenter to JavaScript. An array from ServiceCenter cannot be directly copied into a JavaScript array, because the syntax of ServiceCenter {IM1001, IM1002} does not work in JavaScript. Properties such as the length property assume that the value is a function if it is enclosed in curly braces {}. To successfully convert a ServiceCenter array into a JavaScript array, you can either use the SCFile.toArray method, or create a "while" loop or a "for" loop to move through the elements and do an element-byelement transfer, as shown above. Note: In JavaScript it is very important that you handle null values. Functions such as length may not work on null values.

Programmers reference
This section can be used by JavaScript developers as a reference for: JavaScript global system objects JavaScript global methods JavaScript objects JavaScript methods for the SCFile, SCDatum, and Datum objects JavaScript methods for the XML object JavaScript methods for the XMLDate object

15

JavaScript global system objects


Global objects are predefined objects that are always instantiated and cannot be created using the new operator. Objects may have methods and subordinate properties to which you refer using the dot (.) operator. The primary global object is the System object, which acts as a container for an entire hierarchy of global objects, all of which are properties of the System object. Note: None of the ServiceCenter global system objects have constructors. The following is a complete list of global objects, which are exposed as properties of the System object: system.files system.forms system.functions system.library system.oldrecord system.record system.sysinfo system.sysobjects system.threads system.user system.users system.vars Note: All of the alias or shortcut global objects available in ServiceCenter 6.0 are deprecated in version 6.1 because the alias or shortcut is likely to be used as a script variable. Scripts that attempt to use these names as variables may not function as expected. Therefore, you must type out the entire global system object name, for example, system.user instead of user.

system.files
The system.files JavaScript object is unique to ServiceCenter. It allows you to call a particular ServiceCenter table into memory. Its syntax is: system.files.<table name>. There are no arguments and no methods for the system.files object, and the following property is valid for it:
Property table name Required Yes Description Specifies the table name you want to initialize for processing.

Example This example sets a variable equal to system.files.contacts and displays the contents of the contacts table It requires a valid ServiceCenter table name (for example, contacts) as sample data: var f = system.files.contacts; print( "The value of system.files.contacts is:\n" + f );

system.forms
The system.forms object allows you to call a particular ServiceCenter form into memory. It is unique to ServiceCenter. Its syntax is: system.forms.form_name. There are no arguments or methods for this object, and the following property is valid for it:

16

Property form_name

Required Yes

Description The name of the form you want to bring into memory.

Example This example sets a variable equal to system.forms.ScriptLibrary, and displays the contents of the ScriptLibrary form. It requires a valid ServiceCenter form name (for example, ScriptLibrary) as sample data: var fm = system.forms.ScriptLibrary; print( "The value of system.forms.ScriptLibrary is:\n" + fm );

system.functions
This JavaScript object is unique to ServiceCenter. The system.functions object allows you to call a particular ServiceCenter RAD function from JavaScript. Its syntax is: system.functions.RAD function name( RAD function arguments ). The following argument is valid for this object:
Argument RAD function arguments Data type String Required Yes Description Contains any arguments required to execute the RAD function.

The following property is valid for this object:


Property
RAD function name

Required
Yes

Description
Contains the RAD function name you want to bring into memory.

Example This example sets a variable equal to system.functions.date(), and displays the results of the RAD date() function. It requires a valid ServiceCenter RAD function name (for example, date()) as sample data: fn = system.functions.date(); print( "The value of system.functions.date() is:\n" + fn ); A more complex use of system.functions shows how to insert a logical name value into the first positition of the group.members array: joinFile.group_members = system.functions.insert(joinFile.group_members,0,1, system.vars.$L_file.logical_name);

system.library
The system.library object allows you to call a particular ServiceCenter script library function. It is unique to ServiceCenter. The syntax for this object is: system.library.script name.function name( function arguments ). The following argument is valid for this function:
Argument function arguments Data type String Required Yes Description Contains the function arguments you want to use.

No methods are defined for this object. The following properties are valid for this object:

17

Property script name function name

Required Yes No

Description Contains the name of the script you want to run. Contains the name of the function you want to run.

Example This example calls a script from the Script library. It requires the name of a valid ServiceCenter script (for example, SelfService) as sample data: print( "Runnng script system.library.SelfService..." ) system.library.SelfService.registerEssUser( BOB, HELPDESK, BOB.HELPDESK@acme.com, 858-555-1212 );

system.oldrecord
The system.oldrecord JavaScript object allows you to call the last ServiceCenter record into memory. It is unique to ServiceCenter. Its syntax is: system.oldrecord. There are no arguments, properties, or methods defined for this object. Example The following example sets a variable equal to system.oldrecord, and displays the results of system.oldrecord. o = system.oldrecord; print( "The value of system.record is:\n" + o );

system.record
The system.record JavaScript object allows you to call the current ServiceCenter record into memory. It is unique to ServiceCenter. The syntax for this object is: system.record. There are no arguments, properties, or methods defined for this object. Example This example sets a variable equal to system.record, and displays the results of system.record. r = system.record; print( "The value of system.record is:\n" + r );

system.sysinfo
The system.sysinfo JavaScript object allows you to call an XML list of properties about the ServiceCenter server. It is unique to ServiceCenter. Its syntax is: system.sysinfo. There are no arguments, properties, or methods defined for this object. Example This example sets a variable equal to system.sysinfo, and displays the results of system.sysinfo. s = system.sysinfo; print( "The value of system.sysinfo is:\n" + s );

system.threads
The system.threads JavaScript object allows you to call an XML list of the current ServiceCenter threads into memory. It is unique to ServiceCenter.

18

The syntax is: system.threads There are no arguments, properties, or methods defined for this object. Example This example sets a variable equal to system.threads, and displays the results of system.threads. th = system.threads; print( "The value of system.threads is:\n" + th );

system.user
The system.user JavaScript object allows you to call an XML list of properties of the currently logged on ServiceCenter user. It is unique to ServiceCenter. The syntax is: system.user. There are no arguments, properties, or methods defined for this object. Example This example sets a variable equal to system.user, and displays the results of system.user. u = system.user; print( "The value of system.user is:\n" + u );

system.users
The system.users JavaScript object allows you to call an XML list of the currently logged on ServiceCenter users into memory. It is unique to ServiceCenter. The syntax of this object is: system.users. There are no arguments, properties, or methods defined for this object. Example This example sets a variable equal to system.users, and displays the results of system.users u = system.users; print( "The value of system.users is:\n" + u );

system.vars
The system.vars JavaScript object allows you to call a particular ServiceCenter variable into memory. It is unique to ServiceCenter. Its syntax is: system.vars.variable name There are no arguments or methods for this object. The following property is valid for this object:
Property variable name Required Yes Description Contains the variable name you want to bring into memory.

Example This example sets a variable equal to system.vars.$L_file, and displays the contents of the $L_file variable It requires a valid ServiceCenter variable name (for example, $L_file) as sample data: var v = system.vars.$L_file; print( "The value of system.vars.$L_file is:\n" + t );

19

JavaScript global methods


Global methods are functions that are available to any script; they are not methods of any specific object. You can invoke global methods directly, just as with any core JavaScript global function such as parselnt() or eval().

print
Both displays the contents of the argument ("string" or StringVariable) in the client Messages view, and prints it in the ServiceCenter log file. The syntax is: print ("string") Or print(StringVariable). The print method does not return any value and does not have any throws. The following argument is valid for this function:
Argument "string" or StringVariable Data type output Required Yes Description Contains the text string or variable value you want the script to print to the Message View and the sc.log file. Enclose literal text strings in quotation marks.

Example var example = "abc123."; print ("The value of example is: " + example); This example created the following output: "The value of example is: abc123."

readFile
Reads the contents of a local file and returns a string object with the contents of that file. The file can be in either binary or text format, as specified by the binary argument. The syntax for this method is: readFile( path, binary ). The following arguments are valid for this function:
Argument path Data type String Required Yes Description Contains the text string or variable value containing the fully qualified path of the file to be read. Enclose literal text strings in quotation marks. Determines whether the file format is binary or text. Use the string "b" or "B" to read a binary file. Use any other value to read a text file.

binary

String

Yes

Example This example reads the contents of a text file, and then reads the contents of a binary file. It requires both a text file and a binary file on the local file system as sample data. var textFile = readFile( "C:\\test.xml", "t" ); print( "The value of textFile is: " + textFile ); var binFile = readFile( "C:\\header_left.gif", "b" ); print( "The value of binFile is: " + binFile );

20

writeFile
Writes the contents of the object parameter to a specified path and file, which can be in either binary or text format. It returns the number of bytes written to the file. The syntax for calling this method is: writeFile( path, binary, object ) The following arguments are valid for this function:
Argument path Data type String Required Yes Description Contains the text string or variable value containing the fully qualified path of the file to be written. Enclose literal text strings in quotation marks. Specifies whether the file format is binary or text. Use the string "b" or "B" to write a binary file. Use any other value to write a text file. Contains the text string or variable value containing the data you want to write to a file.

binary object

String String

No Yes

Example This example writes the list of currently logged on users to a file. As sample data it needs the list of currently logged on users stored in system.users. var var var var userList = system.users; filePath; isBinary; fileObject;

function writeToFile( path, binary, object ) { print( "Writing " + path + " to file..." ); var output = writeFile( path, binary, object ); print( "The number of bytes written to file was: " + output ); return output; } filePath = "C:\\users.xml"; isBinary = null; fileObject = userList; writeToFile( filePath, isBinary, fileObject );

Quit
Stops the processing of JavaScript from the point it is called, and returns the failure return code specified in the return code argument. All JavaScript code after the Quit() method call is ignored. The syntax is: Quit( return code ). The following argument is valid for this function:
Argument return code Data type Integer Required Yes Description Contains the numeric return code you want the method to return.

Example This example prints a message, quits, and returns a failure return code: print( "Testing the Quit() method..." ); Quit( -1 ); print( "You won't see this message because the JavaScript has already quit" );

21

base64Encode
Converts binary data to a base-64 string format. You can also use this method to encode plain text data in base-64 format. The method returns a string object with the data in base-64 format. The syntax for using this global method is: base64Encode( data ). The following argument is valid for this method:
Argument data Data type Binary Required Yes Description Contains the data you want the script to encode in base-64 format.

Example This example reads the contents of a binary file, converts the file to a base-64 string format, and prints the base-64 string. It requires a binary file on the local file system (for example, an image file) as sample data: var source = readFile( "C:\\header_left.gif", "b" ); var encode = base64Encode( source ); print( "The value of encode is:\n" + encode );

base64Decode
Converts base-64 string data to its original format. Returns a binary or string object containing the original data. The syntax for this method is: base64Decode( data ). The following argument is valid for this method:
Argument data Data type Binary Required Yes Description Contains the data you want the script to decode to its original format.

Example This example does the following: Reads the contents of a binary file. Converts the file to a base-64 string format. Writes the base-64 string data to a local file. Prints the number of bytes written to the local file system. Reads the contents of a base-64 string format file. Converts the data into a binary file. Writes the binary data to a local file. Prints the number of bytes written to the local file system. This example requires a binary file on the local file system (such as an image file) as sample data: var source = readFile( "C:\\header_left.gif", "b" ); var encode = base64Encode( source ); var encodedFile = writeFile( "C:\\base64EncodedImage.txt", "b", encode ); print( "Wrote " + encodedFile + " bytes to C:\\base64EncodedImage.txt" ); source = readFile( "C:\\base64EncodedImage.txt", "t" ); var decode = base64Decode( source ); var decodedFile = writeFile( "C:\\newImage.gif", "b", decode ); print( "Wrote " + decodedFile + " bytes to C:\\newImage.gif" );

22

xmlstring
Converts a JavaScript string to an XML-formatted string. Does not return a value. The syntax is: xmlstring (string) The following argument is valid for this function:
Argument string Data type String Required No Description Contains the text string or variable value you want the script to convert to an XML string.

Example var xmldoc = new SCFile ( system.users ); xmlstring ( xmldoc ); print ( xmldoc ); Output: <users> <user>falcon</user> </users>

doHTTPRequest
Sends an HTTP request to a remote server specified by a URL. This method returns a string containing an HTTP response or an error message. The syntax for this method is: doHTTPRequest( HTTP command, URL, Headers, POST body, Connect timeout, Send timeout, Receive timeout ) The following arguments are valid for it:
Argument HTTP command URL Headers POST body Connect timeout Data type String String Array String Integer Required Yes Yes Yes No No Description Specifies a command verb such as GET or POST. Specifies the URL to which the script should send an HTTP request. If the HTTP request requires SSL then the URL must start with https. Contains a JavaScript array of ServiceCenter-defined Header objects or an empty array. See the Header object for more information. Contains the body of a POST command request. Specifies the connection timeout threshold in seconds or milliseconds. Use positive integers for second thresholds and negative integers for millisecond thresholds. Use a value of zero for an infinite connection timeout threshold. Specifies the send timeout threshold in seconds or milliseconds. Use positive integers for second thresholds and negative integers for millisecond thresholds. Use a value of zero for an infinite connection timeout threshold. Specifies the receive timeout threshold in seconds or milliseconds. Use positive integers for second thresholds and negative integers for millisecond thresholds. Use a value of zero for an infinite connection timeout threshold.

Send timeout

Integer

No

Receive timeout

Integer

No

Example This example sends an HTTP request to the ServiceCenter Web Services API, and writes the response to a local file. It requires the URL to the ServiceCenter Web Services API as sample data: var url = "http://localhost:12670/IncidentManagement.wsdl"; var headers = new Array(); var IMWSDL = doHTTPRequest( "GET", url, headers, null, 10, 10, 10 );

23

var reply = writeFile( "C:\\IncidentManagement.wsdl", "text", IMWSDL );

doSOAPRequest
Issues a SOAP request to a remote server specified by an URL, and returns the SOAP response in a string or an error message. The syntax for this method is: doSOAPRequest( URL, SOAPAction, XML, SOAP user ID, SOAP password, Connect timeout, Send timeout, Receive timeout, Attachment object ) The following arguments are valid for it:
Argument URL SOAPAction XML Data type String String String Required Yes Yes Yes Description Specifies the URL to which the script should send an HTTP request. If the HTTP request requires SSL, then the URL must start with https. Specifies the SOAP request. Contains the XML for an entire SOAP request including the SOAP envelope. Refer to the Web Service's WSDL to determine the proper format of the SOAP request. Contains the user ID to be used for the Basic Authorization HTTP header. Contains the password value to be used for the Basic Authorization HTTP header. Specifies the connection timeout threshold in seconds or milliseconds. Use positive integers for second thresholds and negative integers for millisecond thresholds. Use a value of zero for an infinite connection timeout threshold. Specifies the send timeout threshold in seconds or milliseconds. Use positive integers for second thresholds and negative integers for millisecond thresholds. Use a value of zero for an infinite connection timeout threshold. Specifies the receive timeout threshold in seconds or milliseconds. Use positive integers for second thresholds and negative integers for millisecond thresholds. Use a value of zero for an infinite connection timeout threshold. Contains a JavaScript array of ServiceCenter-defined Attachment objects or an empty array. See the Attachment object for more information.

SOAP user ID SOAP password Connect timeout

String String Integer

No No No

Send timeout

Integer

No

Receive timeout

Integer

No

Attachment object

Array

No

Example This example sends a SOAP request to a delayed stock quote Web service, and prints the SOAP response to the screen. It requires the following sample data: The URL to a Web-based delayed stock quotation service. The stock symbol for the company. var url = "http://ws.cdyne.com/delayedstockquote/delayedstockquote.asmx"; var action = "http://ws.cdyne.com/GetQuote"; var xml = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:s0=\"http://ws.cdyne.com/\"><soap:Body><GetQuote xmlns=\"http://ws.cdyne.com/\"> <StockSymbol xsi:type=\"s:string\">GOOG</StockSymbol> <LicenseKey xsi:type=\"s:string\">0</LicenseKey> </GetQuote></soap:Body></soap:Envelope>"; var uid = null; var pass = null; var attachments = new Array();

24

var quote = doSOAPRequest( url, action, xml, uid, pass, 10, 10, 10, attachments ); print( "The return value is: " + quote );

makeSCWebURL
This method creates and returns a string containing a URL query to the ServiceCenter Web tier. It does not convert any special characters in the URL (such as spaces or quotation marks) to the characer code equivalent in URL format. You can use the encodeURL method to convert any special characters in the URL. The syntax is makeSCWebURL( Web tier URL, docEngine, table name, query, hash key seed, action, title ) The following arguments are valid for this function:
Argument Data type Required Description This argument specifies the fully qualified URL to the ServiceCenter Web tier. This URL must include the http:// protocol syntax as well as the server name or IP address and communications port number. This argument specifies that the query should be handled by the ServiceCenter Document Engine. This argument does not accept any other string value. This argument specifies the table where the Document Engine should query for records. This argument specifes the ServiceCenter query you want to use to search for records. The query should be in the ServiceCenter server's system language format. This argument specifies an optional string you want to use to create a unique hash key. The hash key seed does not appear in the final URL produced. This argument specifies the Document Engine action you want the URL query to perform. By default, the URL query performs a search operation. This argument specifies the optional title.

Web tier URL

String

Yes

docEngine

String

Yes

table name

String

Yes

query

String

Yes

hash key seed

String

No

action title

String String

No No

Example This example creates a URL query to the ServiceCenter Web tier and converts any special characters in the URL to valid URI format. It requires the following sample data: The URL to ServiceCenter Web tier A valid ServiceCenter table name (for example, incidents) A valid ServiceCenter query against the table (for example, incident.id="SD1001") function createURLquery( table, query, title ) { var url; var webtier; var webserver; var doceng; var hashkey; var action; webserver = "http://<servername>/sc/index.do"; doceng = "docEngine"; hashkey = ""; action = ""; webtier = makeSCWebURL( webserver, doceng, table,

25

query, hashkey, action, title ); print( "Creating URL from information provided..." ); print( "The value of webtier is:\n" + webtier ); print( "Converting special characters in URL to valid URI format..." ); url = encodeURI( webtier ); print( "The value of url is:\n" + url ); return url; } var tablename = "incidents" var SCquery = "incident.id=\"SD1001\"" var titlename = "Interaction SD1001" createURLquery( tablename, SCquery, titlename );

help
Displays a brief description of a ServiceCenter-defined JavaScript object. Requires the use of the print() method to see the help text string. Returns a brief text string describing the ServiceCenterdefined JavaScript object, or returns null if no help is available. The syntax is: help( object ). The following argument is valid for this function:
Argument object Data type ServiceCenter-defined JavaScript object Required Yes Description Contains the ServiceCenter-defined JavaScript object for which you want a brief description.

Example This example displays the help contents of several ServiceCenter-defined JavaScript objects var f = new SCFile(); print( help( f ) ); var x = new XML(); print( help( x ) ); var d = new XMLDate(); print( help( d ) );

RCtoString
Converts a ServiceCenter global return code value into a localized text string. The syntax is: RCtoString( return code ). The following argument is valid for this function:
Argument return code Data type Integer Required Yes Description Contains the ServiceCenter global return code value that you want to convert to a localized string.

Example This example searches the contacts table for any contact name you define in the search variable, and displays the contact record as a text string. It requires the following sample data: A valid contact name (such as "FALCON, JENNIFER") and an invalid contact name (such as "NOT A, CONTACT"). var contactName; function findContactName( name ) {

26

print( "Searching for contact: " + name + "..." ); var contactList = new SCFile( "contacts" ); var findContact = contactList.doSelect( "contact.name=\""+ name + "\"" ) if ( findContact == RC_SUCCESS ) { print( "Success. found " + name + " in contact record:\n" + contactList.getText() ); return contactList; } else { print( "Could not find contact. " + RCtoString( findContact ) ); return null; } } contactName = "FALCON, JENNIFER"; findContactName( contactName ); contactName = "NOT A, CONTACT"; findContactName( contactName );

execute
Validates the syntax of a JavaScript and displays the message "Successful compilation of JavaScript function or expression" if the JavaScript passes validation; otherwise displays an error message. The compile() method is an alias of the execute() method. The syntax for this method is: execute( script, description ). No throws are defined for it, and the following arguments are valid for it:
Argument script description Data type String String Required Yes No Description Contains the name of the script you want to validate. Use this argument to store any comments you want.

Example This example creates a variable to store a JavaScript name, and validates the contents of the script. It requires a valid JavaScript for sample data: var s = "lib.SCFILEgetTextTest"; excute( s, "Testing execute" );

compile
Validates the syntax of a JavaScript and displays the message "Successful compilation of JavaScript function or expression" if the JavaScript passes validation; otherwise displays an error message. The compile() method is an alias of the execute() method. The syntax for this method is compile( script, description ). No throws are defined for compile(). The following arguments are valid for it:
Argument script description Data type String String Required Yes No Description Contains the name of the script you want to validate. Use this argument to store any comments you want.

Example This example creates a variable to store a JavaScript name, and validates the contents of the script. It requires a valid JavaScript for sample data: var s = "lib.SCFILEgetTextTest"; compile( s, "Testing execute" );

27

JavaScript objects
Attachment
This object is unique to ServiceCenter and contains attachment data for use with doSOAPRequest methods. You can use the readFile global method to add data to the Attachment object. You can use the push method to add Attachment objects to a JavaScript array. The constructor is: new Attachment(); No arguments are passed into the object. The following properties are valid for it:
Property value len href action Data type Binary Integer String String Description Contains the binary data of the attachment. Contains the length of the binary data in bytes. Contains the unique identifier for the attachment in the SOAP request message. Contains the name of action to take with the attachment in ServiceCenter Web Services ServiceCenter API. The following options are available:


name type attachmentType String String String

add Adds the specified attachment. remove Removes the specified attachment. get Retreives the specified attachment. update Updates the specified attachment.

Contains the name of the attachment, which is typically a file name. Contains the MIME type of the attachment. Pertains only to ServiceCenter attachments, and contains the attachment type as defined in ServiceCenter. If present, and if the property has a value of "img," then the attachment must also have a MIME type of "image/bmp".

There are no methods defined for this object. Example var a = new Attachment(); var source = readFile( "C:\\header_left.gif", "b" ); a.value = source; a.name = "C:\\header_left.gif"; print( "The value of a is: " + a ); print( "Setting attachment value to source: " + a.name ); print( "The size of the attachment is: " + a.len + " bytes" );

Header
With no arguments, the Header() constructor, new Header(), creates an empty Header object. With the HTTP header arguments, the Header() constructor, new Header(Header type, Header value) creates an Header object containing the provided header types and values. Always enclose header types and header values in quotation marks. This JavaScript object is unique to ServiceCenter. The following arguments are valid for it:
Argument Header type Header value Description The HTTP header type, such as "Accept-Encoding" or "Content-Type". The HTTP header value, such as "gzip,deflate" or "text/html".

28

No properties or methods are defined for this object. Example var h = new Header( "Accept-Encoding", "gzip,deflate" ); var hd = new Header(); hd.name = "Content-Type"; hd.value = "text/html"; var headers = new Array(); headers.push( hd );

Datum
The Datum JavaScript object is unique to ServiceCenter. You can use the SCFile or SCDatum objects in place of this object to take advantage of the improved return code values. Note: The Datum Object was deprecated as of ServiceCenter 6.1 because this object's methods can return only Boolean values. It is still often used to access ServiceCenter arrays. With no parameters, the Datum() constructor, new Datum() creates an empty Datum object. When an Object parameter is used with the Datum() constructor, new Datum(Object) creates a ServiceCenter-formatted Datum object containing the specified record, structure, or array. Always enclose table names and arrays in quotation marks. You can use the Datum object as a parameter for RTECall routines that expect ServiceCenter-formatted parameters. The following argument is valid for this object:
Argument Object Data type String Description The ServiceCenter table name, record, structure, or array you want to query or update.

This object has no properties. The following methods are valid for it. Note: Detailed instructions for these methods can be found in the section JavaScript methods for the SCFile, SCDatum, and Datum objects.
Method Name doAction doDelete doInsert doRemove doSave doSelect doUpdate getFirst getLast getNext getPrev getSize Description Executes a method defined on the object. Synonymous with the doRemove method, this method simply has a more intuitive name. Inserts an object into the database. Removes an object from the database. Inserts a record if it is new, and updates the record if it already exists. Makes a query. It no longer requires that the first argument be the name of the table if the object is constructed with the name of the table. Updates the database. Moves to the first record if the object represents a result set. Moves to the last record if the object represents a result set. Moves to the next record if the object represents a result set. Moves to the previous record if the object represents a result set. Returns the size of the object.

29

Method Name getText getType getXML isRecord join JSDate length pop push setType setValue shift toArray unshift

Description Returns a text representation of the object. Returns the object type. Returns an XML representation of the object. Checks whether an object represents a current table and has a record. Returns a string of all the entries in the array. Returns a JavaScript Date object. Returns the length of the object. Removes an item from an array. Adds an item to an array. Sets the object type. Sets the object to a given value. Returns a string of all the entries in the array. Converts an object to a JavaScript array. Returns a string of all the entries in the array.

Example var q = new Datum("contacts"); if ((q.soSelect('contact.name # "B"')) == true) { print (q.getText()); { else { print("No contacts start with B"); }

SCDatum
SCDatum, which is unique to ServiceCenter, is an alias of the SCFile object. When used with no parameters, the SCDatum() constructor, new SCDatum() creates an empty SCDatum object. When used with the object parameter, the SCDatum() constructor, new SCDatum(object) creates an SCDatum object containing the specified record, structure, or array. Always enclose table names and arrays in quotation marks. This object's methods use the ServiceCenter-defined global return codes. The following argument is valid for this object:
Argument object Description The table name, record, structure, or array you want to query or update.

No properties are defined for this object. The following methods are valid for it: Note: Detailed instructions for these methods can be found in the section JavaScript methods for the
SCFile, SCDatum, and Datum objects.

30

Method Name doAction doDelete doInsert doRemove doSave doSelect doUpdate getFirst getLast getNext getPrev getSize getText getType getXML isRecord join JSDate length pop push setType setValue shift toArray unshift

Description Executes a method defined on the object. Synonymous with the doRemove method, this method simply has a more intuitive name. Inserts an object into the database. Removes an object from the database. Inserts a record if it is new and updates the record if it already exists. Makes a query. It no longer requires that the first argument be the name of the table if the object is constructed with the name of the table. Updates the database. Moves to the first record if the object represents a result set. Moves to the last record if the object represents a result set. Moves to the next record if the object represents a result set. Moves to the previous record if the object represents a result set. Returns the size of the object. Returns a text representation of the object. Returns the object type. Returns an XML representation of the object. Checks whether an object represents a current table and has a record. Returns a string of all the entries in the array. Returns a JavaScript Date object. Returns the length of the object. Removes an item from an array. Adds an item to an array. Sets the object type. Sets the object to a given value. Returns a string of all the entries in the array. Converts an object to a JavaScript array. Returns a string of all the entries in the array.

Example var q = new SCDatum("contacts"); if ((q.doSelect('contact.name # "B"')) == RC_SUCCESS) { print (q.getText()); } else { print("Return code is: " + q.RCtoString); }

SCFile
The SCFile JavaScript object is unique to ServiceCenter. When called with no parameters, the SCFile() constructor, new SCFile()

31

creates an empty SCFile object. When called with an object parameter, the SCFile() constructor, new SCFile(object) creates an SCFile object containing the specified record, structure, or array. Always enclose table names and arrays in quotation marks. This object's methods use the ServiceCenter-defined global return codes. The following argument is valid for this object:
Argument object Data type String Description The table name, record, structure, or array you want to query or update.

No properties are defined for this object. The following methods are valid for it: Note: Detailed instructions for these methods can be found in the section JavaScript methods for the SCFile, SCDatum, and Datum objects.
Method Name doAction doDelete doInsert doRemove doSave doSelect doUpdate getFirst getLast getNext getPrev getSize getText getType getXML isRecord join JSDate length pop push setType setValue shift Description Executes a method defined on the object. Synonymous with the doRemove method, doDelete simply has a more intuitive name. Inserts an object into the database. Removes an object from the database. Inserts a new record, or updates an existing record. Makes a query. It no longer requires that the first argument be the name of the table if the object is constructed with the name of the table. Updates the database. Moves to the first record if the object represents a result set. Moves to the last record if the object represents a result set. Moves to the next record if the object represents a result set. Moves to the previous record if the object represents a result set. Returns the size of the object. Returns a text representation of the object. Returns the object type. Returns an XML representation of the object. Checks whether an object represents a current table and has a record. Returns a string of all the entries in the array. Returns a JavaScript Date object. Returns the length of the object. Removes an item from an array. Adds an item to an array. Sets the object type. Sets the object to a given value. Returns a string of all the entries in the array.

32

Method Name toArray unshift

Description Converts an object to a JavaScript array. Returns a string of all the entries in the array.

Example var q = new SCFile("contacts"); if ((q.doSelect('contact.name # "B"')) == RC_SUCCESS) { print (q.getText()); } else { print("Return code is: " + q.RCtoString); }

XML
The XML() constructor, new XML(), creates an empty XML object where you can store and manipulate XML documents. This object's methods do not use the ServiceCenter-defined global return codes. The XML JavaScript object is unique to ServiceCenter. No properties are defined for the method, and it accepts no arguments. The following methods are valid for this object. Note: Detailed instructions for these methods can be found in the section JavaScript methods for the XML object.
Method Name addAttribute addElement appendNode createNode getAttributeNode getAttributeValue getDocumentElement getFirstAttribute getFirstChildElement getName getNextAttribute getNextSiblingElement getNodeName getNodeType getNodeValue getParentNode getPrefix getQualifiedName Description Inserts an XML attribute and attribute value into the current element. Inserts an XML element as a child of the current element. Inserts an XML node into an XML object. Creates an XML node from an XML object. Returns an XML object containing an attribute node. Returns the value of the target attribute. Creates an XML object containing the document element and all child elements from an XML object or XML string. Returns an XML object representing the first attribute of the current node. Returns an XML object representing the first child node of the current node. Returns a string representing the name of the current element or attribute. Returns an XML object representing the next attribute of the current node. Returns an XML object representing the next node at the same level in the Document Object Model (DOM) tree as the current node. Returns a string representing the name of the current element or attribute. Evaluates an XML object and returns an integer representing the XML Document Object Model (DOM) type of the current element or attribute. Returns a string representing the value of the current element. Returns an XML object representing the parent node of the current node. Returns a string representing the namespace value of the current element or attribute. Returns a string representing the name of the current element or attribute including any namespace value.

33

Method Name getText getValue importNode isDocumentElement setAttributeValue setContent setNodeValue setText setValue toXMLString

Description Returns a string representing the value of the current element. Returns a string representing the value of the current element. Copies an XML node from one XML document to another. Returns true if the current element is the Document Object Model (DOM) document element. Adds or updates an attribute value. Creates an XML document from a string or file. Adds or updates the value of the current element. Adds or updates the value of the current element. Adds or updates the value of the current element. Converts an XML object into a valid XML string.

Example /* Instantiate an empty XML object */ var xmlObj = new XML(); /* Instantiate a variable containing the path to an XML file */ var xmlFile = "C:\\myxmldoc.xml"; /* Use setContent to make the XML object read and parse the XML file * If the setContent method fails, print an error message */ if ( ! xmlObj.setContent( xmlFile, true ) ) { print( "setContent failed. Unable to parse xml: " + xmlFile ); }

XMLDate
The XMLDate JavaScript object is unique to ServiceCenter. It has no arguments, and the XMLDate() constructor, new XMLDate() creates an empty XMLDate object. When used with a DateObject argument, the XMLDate() constructor, new XMLDate(DateObject) converts a JavaScript date object to an XMLDate object. When used with an ISO8601DateTimeOrDurationString argument, the XMLDate() constructor, new XMLDate(ISO8601DateTimeOrDurationString) converts an XML schema date object to an XMLDate object. When used with a DateTimeDatum argument, the XMLDate() constructor, new XMLDate(DateTimeDatum) converts a ServiceCenter date object to an XMLDate object. This object's methods use the ServiceCenter-defined global return codes. The following arguments are valid for this object:

34

Argument DateObject ISO8601DateTimeOrDurationString DateTimeDatum

Data type JavaScript date object XML schema date ServiceCenter Datum object

Description Passes a JavaScript date object to the XMLDate constructor. Passes an XML schema date, time, datetime, or duration string to the XMLDate constructor. Passes a ServiceCenter datum object formatted as a TIME type to the XMLDate constructor.

Note: Some of the JavaScript date object times / days start with 0 instead of 1; or the year starts with 1900. For example, using the getMonth, getDate and getYear methods, December 31st 2005 would be represented as 11-31-105.
Value Seconds and minutes Hours Day Date Months Year Integer 0 through 59 0 through 23 0 through 6 (day of the week) 1 through 31 (day of the month) 0 (January) through 11 (December) Number of years since 1900

No properties are defined for the XMLDate object. The following methods are valid for it: Note: Detailed instructions for these methods can be found in the section JavaScript methods for the
XMLDate object.
Method Name addDuration(iso8601durationstring) getDate getDatum getGMTSCDateTimeString getISODate getISODateTimeString getISODay getISOMonth getISOTime getISOYear getSCDateTimeString JSDate toSCDuration Description Adds the indicated duration to the contained value in the XMLDate object. Returns a JavaScript date object (same as the JSDate method). Returns an SCDatum object Returns the Greenwich Mean Time (GMT) date time in ServiceCenter format. Returns the indicated portions of the XMLDate value. Passes a JavaScript Date object to the constructor. Returns the indicated portions of the XMLDate value. Returns the indicated portions of the XMLDate value. Returns the indicated portions of the XMLDate value. Returns the indicated portions of the XMLDate value. Returns a date time string in ServiceCenter format. Returns a Javascript date object. Converts an ISO duration string to a ServiceCenter duration.

Example /* Instantiate a new SCFile object with records of the cm3r table */ var changeRequest = new SCFile("cm3r"); /* Set the ServiceCenter fields date.entered and planned.start to today's date.

35

* The dots in ServiceCenter field names must be converted to underscores */ var theXMLDate = new XMLDate( new Date() ); var todaysDate = theXMLDate.getDatum(); changeRequest.header.date_entered = todaysDate; changeRequest.header.planned_start = todaysDate; /* Increment the value of the planned.end field to be a week later. * P is the addDuration parameter for duration * 7D is the addDuration parameter for 7 days * See the addDuration method for additional information */ theXMLDate.addDuration('P7D'); var nextWeeksDate = theXMLDate.getDatum(); changeRequest.header.planned_end = nextWeeksDate; changeRequest.doInsert();

JavaScript methods for the SCFile, SCDatum, and Datum objects


SCFile.doAction()
This method executes a Document Engine action using any new field values defined in a ServiceCenter file object. It requires that you define a ServiceCenter file object, and may also require that you define new values for required fields. The method returns RC_SUCCESS if the method successfully runs the Document Engine action; or returns one of the error global return code values if the method cannot run the Document Engine action. The syntax for this method is doAction( docEngineAction ). The following argument is valid for this method:
Argument docEngineAction Data type String Description Specifies the Document Engine action you want the script to execute on the object. Must contain a valid ServiceCenter Document Engine action appropriate for the ServiceCenter object.

Example This example creates a new incident record from variable values, and resolves the incident record. It requires that the "Use Resolved Status?" option be enabled in the Incident Management Environment record; and that a valid value (such as "IM11112") populate the number field. var var var var var var var numberValue; callbackContact; categoryValue; descriptionValue; actionType; resultionCodeValue; resolutionValue;

function insertIncident( num, name, cat, desc ) { print( "Creating new incident record..." ); var newIncident = new SCFile( "probsummary" ); newIncident.number = num; newIncident.callback_contact = name; newIncident.category = cat; newIncident.description = desc; var rc = newIncident.doInsert(); if ( rc == RC_SUCCESS ) { print( "Success. Created new record " + newIncident.getText() ); return newIncident.number;

36

} else { print( "Could not create record. " + RCtoString( rc ) ); return null; } } function closeIncident( id, action, rescode, res ) { print( "Resolving incident " + id + "..." ); var findIncident = new SCFile ( "probsummary" ); var f = findIncident.doSelect( "number=\"" + id + "\"" ); if ( f == RC_SUCCESS ) { print( "Success. Found iteraction record..." ); findIncident.resolution_code = rescode; findIncident.resolution = res; var a = findIncident.doAction( action ); print( "The resolve Incident return value is " + RCtoString( a ) ); print( "The incident record is " + findIncident.getText() ); print( "The value of the status field is: " + findIncident.problem_status ); return findIncident; } else { print( "Could not find record. " + RCtoString( f ) ); return null; } } numberValue = "IM11112"; callbackContact = "FALCON, JENNIFER"; categoryValue = "network"; descriptionValue = null; interactionID = insertIncident( numberValue, callbackContact, categoryValue, descriptionValue ); actionType = "resolve"; resultionCodeValue = "Advice & Guidance"; resolutionValue = null; closeIncident( interactionID, actionType, resultionCodeValue, resolutionValue );

SCFile.doDelete()
This method removes a ServiceCenter record with any new field values defined in a ServiceCenter file object. It requires that you define both a ServiceCenter file object and new values for fields. It is a synonym of the doRemove() method. The method returns RC_SUCCESS if the method successfully removes a record; or returns one of the error global return code values if the method cannot remove the record. The syntax for this method is doDelete() and there are no arguments for it. Example This example searches the probsummary table for any interaction record you define in the search variable, and removes the interaction record. It requires as sample data a valid value such as "IM11111" in the number field. var numberValue; function removeInteraction( num )

37

{ print( "Removing interaction record..." ); var interactionRecord = new SCFile( "probsummary" ); var findRecord = interactionRecord.doSelect( "number=\"" + num + "\""); print( "The interaction record is " + interactionRecord ); var rc = interactionRecord.doDelete(); if ( rc == RC_SUCCESS ) { print( "Success. Removed record " + interactionRecord.getText() ); return interactionRecord; } else { print( "Could not remove record. " + RCtoString( rc ) ); return null; } } numberValue = "IM11111"; removeInteraction( numberValue );

SCFile.doInsert()
This method creates a ServiceCenter record with any new field values defined in a ServiceCenter file object. It requires that you define both a ServiceCenter file object and new values for fields. The syntax for this method is doInsert() No arguments are passed. The method returns RC_SUCCESS if the method successfully creates a record; or returns one of the error global return code values if the method cannot create the record. Example This example searches the probsummary table for any incident record you define in the search variable, and displays the new incident record as a text string. This example requires the following sample data: A valid value for the number field (for example, "IM11111") A valid value for the callback.contact field (for example, "FALCON, JENNIFER") A valid value for the category field (for example, "network") var var var var numberValue; callbackContact; categoryValue; descriptionValue;

function insertContact( num, name, cat ) { print( "Creating new interaction record..." ); var newInteraction = new SCFile( "probsummary" ); newInteraction.number = num; newInteraction.callback_contact = name; newInteraction.category = cat; var rc = newInteraction.doInsert(); if ( rc == RC_SUCCESS ) { print( "Success. Created new record " + newInteraction.getText() ); return newInteraction; } else { print( "Could not create record. " + RCtoString( rc ) );

38

return null; } } numberValue = "IM11112"; callbackContact = "FALCON, JENNIFER"; categoryValue = "network"; insertContact( numberValue, callbackContact, categoryValue, descriptionValue );

SCFile.doRemove()
This method removes a ServiceCenter record with any new field values defined in a ServiceCenter file object. It requires that you define both a ServiceCenter file object and new values for fields. The syntax for this method is doRemove() No arguments are passed. The method returns RC_SUCCESS if the method successfully removes a record; or returns one of the error global return code values if the method cannot remove the record. Example This example searches the probsummary table for an interaction record you define in the search variable, and removes the interaction record. It requires a valid value such as "IM11111" for the number field as sample data: var numberValue; function removeInteraction( num ) { print( "Removing interaction record..." ); var interactionRecord = new SCFile( "probsummary" ); var findRecord = interactionRecord.doSelect( "number=\"" + num + "\""); print( "The interaction record is " + interactionRecord ); var rc = interactionRecord.doRemove(); if ( rc == RC_SUCCESS ) { print( "Success. Removed record " + interactionRecord.getText() ); return interactionRecord; } else { print( "Could not remove record. " + RCtoString( rc ) ); return null; } } numberValue = "IM11111"; removeInteraction( numberValue );

SCFile.doSave()
This method adds to or updates the ServiceCenter database with any new field values defined in a ServiceCenter file object. It requires that you define both a ServiceCenter file object and new values for fields. The syntax is doSave() No arguments are passed.

39

The method returns RC_SUCCESS if the method successfully updates a record; or returns one of the error global return code values if the method cannot update the record. Example This example does the following: Searches the contacts table for a contact name you define in the search variable. Displays the contact record as a text string. Updates the value of the user.type field. Saves the ServiceCenter record. This example requires the following sample data: A valid contact name (for example, "FALCON, JENNIFER") A valid field value update (for example, set the user.type field to "site") var contactName; function updateContact( name ) { print( "Searching for contact: " + name + "..." ); var contactList = new SCFile( "contacts" ); var isContact = contactList.doSelect( "contact.name=\""+ name + "\"" ); if ( isContact == RC_SUCCESS ) { print( "Success. found " + name + " in contact record:\n" + contactList.getText() ); print( "The current contents of the user.type field are: " + contactList.user_type ); print( "Updating the user.type field..." ); contactList.user_type = "site"; print( "Saving record..." ); var rc = contactList.doSave(); print( "The return code value for the doSave() method is: " + RCtoString( rc ) ); print( "The contents of the user.type field are now: " + contactList.user_type ); return contactList; } else { print( "Could not find contact. " + RCtoString( isContact ) ); return null; } } contactName = "FALCON, JENNIFER"; updateContact( contactName );

SCFile.doSelect(query)
This method runs a specified query and returns a list of records that match the query's selection criteria. The method returns an SCFile object containing the records matching the query, and a global return code value of RC_SUCCESS; or returns one of the error global return code values if the method cannot return any records. The SCFile object that is returned after successful query execution has the following format: table={ ["field value",{"array value_1","array value_2",,.array value_n..} ] } The syntax is doSelect( "query" )

40

The following argument is valid for this method:


Argument query Data type String Description Specifies the query you want to use to search for ServiceCenter records. Precede special characters such as quotation marks with a backslash (\), which acts as an escape character.

Example This example searches the contacts table for any contact name you define in the search variable and displays the contact record as a text string. This example requires the following sample data: A valid contact name (for example, "FALCON, JENNIFER") A invalid contact name (for example, "NOT A, CONTACT") var contactName; function findContactName( name ) { print( "Searching for contact: " + name + "..." ); var contactList = new SCFile( "contacts" ); var findContact = contactList.doSelect( "contact.name=\""+ name + "\"" ); if ( findContact == RC_SUCCESS ) { print( "Success. found " + name + " in contact record:\n" + contactList.getText() ); return contactList; } else { print( "Could not find contact. " + RCtoString( findContact ) ); return null; } } contactName = "FALCON, JENNIFER"; findContactName( contactName ); contactName = "NOT A, CONTACT"; findContactName( contactName );

SCFile.doUpdate()
This method updates a ServiceCenter record with any new field values defined in a ServiceCenter file object. This method requires that you define both a ServiceCenter file object and new values for fields. The syntax for this method is doUpdate() No arguments are passed. The method returns RC_SUCCESS if the method successfully updates a record; or returns one of the error global return code values if the method cannot update the record. Example This example searches the contacts table for any contact name you define in the search variable, and displays the contact record as a text string. This example requires the following sample data: A valid contact name (for example, "FALCON, JENNIFER")

41

A valid field value update (for example, set the user.type field to "site") var contactName; function updateContact( name ) { print( "Searching for contact: " + name + "..." ); var contactList = new SCFile( "contacts" ); var isContact = contactList.doSelect( "contact.name=\""+ name + "\"" ); if ( isContact == RC_SUCCESS ) { print( "Success. found " + name + " in contact record:\n" + contactList.getText() ); print( "The current contents of the user.type field are " + contactList.user_type ); print( "Updating the user.type field..." ); contactList.user_type = "site"; contactList.doUpdate(); print( "The contents of the user.type field are now " + contactList.user_type ); return contactList; } else { print( "Could not find contact. " + RCtoString( isContact ) ); return null; } } contactName = "FALCON, JENNIFER"; updateContact( contactName );

SCFile.getFirst()
This method returns the first record in a record list stored in an SCFile object. It requires that you use the other SCFile methods to create a record list. The syntax for the method is getFirst() No arguments are passed. The method returns an SCFile object containing the first record in a record list and a global return code value of RC_SUCCESS; or returns one of the error global return code values if the method cannot find the first record. Example This example does the following: Queries the contacts table for any contact name you define in the search variable. Displays the last record in the record list. Displays the previous record in the record list. Displays the first contact in the record list. This example requires the following sample data: A contact query that produces a record list (for example, "B") A contact query that produces a single record (for example, "F") var contactQuery; function findFirstContact( query ) { print( "Searching for contacts starting with " + query + "..." );

42

var contactFile = new SCFile( "contacts" ); var findContact = contactFile.doSelect( "contact.name#\""+ query + "\"" ); if ( findContact == RC_SUCCESS ) { print( "Success. Found contacts starting with " + query + "." ); var findLastRecord = contactFile.getLast(); print( "The last record is:\n" + contactFile ); var findPrevRecord = contactFile.getPrev(); print( "The previous record is:\n" + contactFile ); var findFirstRecord = contactFile.getFirst(); print( "The first record is:\n" + contactFile ); } else { print( "Could not find contacts starting with " + query + ". " + RCtoString( findContact ) ); return null; } } contactQuery = "H"; findFirstContact( contactQuery );

SCFile.getLast()
This method returns the last record in a record list stored in an SCFile object. It requires the use of the other SCFile methods to create a record list. The syntax of this method is getLast(). No arguments are passed. The method returns an SCFile object containing the last record in a record list, and a global return code value of RC_SUCCESS; or returns one of the error global return code values if the method cannot find the last record. Example This example does the following: Queries the contacts table for any contact name you define in the search variable. Displays the first contact in the record list. Displays the last record in the record list. This example requires the following sample data: A contact query that produces a record list (for example, "B") A contact query that produces a single record (for example, "F") var contactQuery; function findLastContact( query ) { print( "Searching for contacts starting with " + query + "..." ); var contactFile = new SCFile( "contacts" ); var findContact = contactFile.doSelect( "contact.name#\""+ query + "\"" ); if ( findContact == RC_SUCCESS ) { print( "Success. Found contacts starting with " + query + ". The first record is:\n" + contactFile ); var findLastRecord = contactFile.getLast(); print( "The last record is:\n" + contactFile ); return contactFile; } else { print( "Could not find contacts starting with " + query + ". " + RCtoString( findContact ) ); return null; } }

43

contactQuery = "H"; findLastContact( contactQuery ); contactQuery = "F"; findLastContact( contactQuery );

SCFile.getNext()
This method returns the next record in a record list stored in an SCFile object. It requires the use of the other SCFile methods to create a record list. The syntax of this method is getNext() No arguments are passed. The method returns an SCFile object containing the next record in a record list and a global return code value of RC_SUCCESS; or returns one of the error global return code values if the method cannot find the next record. Example This example does the following: Queries the contacts table for any contact name you define in the search variable. Displays the first contact in the record list. Displays the next record in the record list. This example requires the following sample data: A contact query that produces a record list (for example, "B") A contact query that produces a single record (for example, "F") var contactQuery; function findNextContact( query ) { print( "Searching for contacts starting with " + query + "..." ); var contactFile = new SCFile( "contacts" ); var findContact = contactFile.doSelect( "contact.name#\""+ query + "\"" ); if ( findContact == RC_SUCCESS ) { print( "Success. Found contacts starting with " + query + ". The first record is:\n" + contactFile.getText() ); var findNextRecord = contactFile.getNext(); print( "The next record is:\n" + contactFile.getText() ); return contactFile; } else { print( "Could not find contact " + query + ". " + RCtoString( findContact ) ); return null; } } contactQuery = "B"; findNextContact( contactQuery ); contactQuery = "F"; findNextContact( contactQuery );

SCFile.getPrev()
This method returns the previous record in a record list stored in an SCFile object. It requires that you use the other SCFile methods to create a record list. The syntax is getPrev(). No arguments are passed.

44

The method returns an SCFile object containing the previous record in a record list and a global return code value of RC_SUCCESS; or returns one of the error global return code values if the method cannot find the previous record. Example This example does the following: Queries the contacts table for any contact name you define in the search variable. Displays the first contact in the record list. Displays the last record in the record list. Displays the previous record in the record list. This example requires a contact query that produces a record list (such as contact names starting with H), and it requires appropriate sample data. var contactQuery; function findPrevContact( query ) { print( "Searching for contacts starting with " + query + "..." ); var contactFile = new SCFile( "contacts" ); var findContact = contactFile.doSelect( "contact.name#\""+ query + "\"" ); if ( findContact == RC_SUCCESS ) { print( "Success. Found contacts starting with " + query + ". The first record is:\n" + contactFile ); var findLastRecord = contactFile.getLast(); print( "The last record is:\n" + contactFile ); var findPrevRecord = contactFile.getPrev(); print( "The previous record is:\n" + contactFile ); } else { print( "Could not find contacts starting with " + query + ". " + RCtoString( findContact ) ); return null; } } contactQuery = "H"; findPrevContact( contactQuery );

SCFile.getSize()
This method returns the number of array elements in an array stored in a ServiceCenter Datum object. You can use this method to return the length of ServiceCenter array fields, which are always stored as Datum objects. To query a particular array field in an SCFile object, you can use the following format: SCFile_object.array_field_name.getSize() Replace any periods in the name of array_field_name with underscores. For example, you convert the ServiceCenter array field update.action to "update_action" when querying it from JavaScript. The syntax is: Datum_object.getSize(). No arguments are passed. The method returns the number of array elements in an array stored in a ServiceCenter Datum object and a global return code value of RC_SUCCESS; or returns one of the error global return code values if the method cannot return the number of array elements.

45

Example This example does the following: Searches the probsummary table for any incident record you define in the search variable. Attempts to get the size of the returned SCFile object (the result is always zero). Displays the contents of the action field (the action field contains ServiceCenter array data). Displays the size of the action field using the ServiceCenter getSize() method. Converts the SCFile object into a JavaScript array using the ServiceCenter toArray() method. Displays the size of the new JavaScript array using the core JavaScript length property. This example requires as sample data a valid incident record number, such as "IM1005". var incidentQuery; function findIncidents( query ) { print( "Searching for incident records starting with " + query + "..." ); var incidentFile = new SCFile( "probsummary" ); var findIncident = incidentFile.doSelect( "number#\""+ query + "\"" ); if ( findIncident == RC_SUCCESS ) { print( "Success. Found incident records starting with " + query + ". The first record is:\n" + incidentFile ); var objectSize = incidentFile.getSize(); print( "Running the getSize() method on the returned SCFile object produces the following result: " + objectSize ); var actionText = incidentFile.action; print( "The contents of the action field is:\n" + actionText ); var actionSize = incidentFile.action.getSize(); print( "The size of the action field is: " + actionSize ); print( "Converting the SCFile object to a JavaScript array..." ); var incidentArray = incidentFile.toArray(); print( "The new JavaScript array is:\n" + incidentArray ); var arraySize = incidentArray.length; print( "The size of the converted array is: " + arraySize ); return incidentFile; } else { print( "Could not find incident records starting with " + query + ". " + RCtoString( findIncident ) ); return null; } } incidentQuery = "IM1005"; findIncidents( incidentQuery );

SCFile.getText()
This method returns a text string of the current SCFile object. The text string has the following format: table= { [ "field value", {"array value_1","array value_2","array value_N}.] } The syntax is getText() No arguments are passed. The method returns a text string containing the current SCFile object, and a global return code value of RC_SUCCESS; or returns one of the global error return code values if the method cannot return a string.

46

Example This example searches the contacts table for any contact name you define in the search variable, and displays the contact record as a text string. It requires the following sample data: A valid contact name (for example, "FALCON, JENNIFER") A invalid contact name (for example, "NOT A, CONTACT") var contactName; function findContactName( name ) { print( "Searching for contact: " + name + "..." ); var contactList = new SCFile( "contacts" ); var findContact = contactList.doSelect( "contact.name=\""+ name + "\"" ) if ( findContact == RC_SUCCESS ) { print( "Success. found " + name + " in contact record:\n" + contactList.getText() ); return contactList; } else { print( "Could not find contact. " + RCtoString( findContact ) ); return null; } } contactName = "FALCON, JENNIFER"; findContactName( contactName ); contactName = "NOT A, CONTACT"; findContactName( contactName );

SCFile.getType()
This method returns the data type of ServiceCenter SCFile objects such as arrays and structured arrays. It fails on any scalar fields within file records, such as number, date, string, and Boolean fields. To determine the type of scalar fields you can use, use the core JavaScript ".type" property. The syntax for this method is getType() No arguments are passed. The method returns a data type and a global return code value of RC_SUCCESS; or returns one of the error global return code values if the method cannot determine the data type. Example This example does the following: Searches the probsummary table for any incident record you define in the search variable. Displays the contents of the incident record object. Returns the data type of the incident record object using the getType() method. Displays the contents of the action field object. Returns the data type of the action field object using the getType() method. Displays the contents of the category field. Displays the contents of the category field. This example requires a valid incident record (such as "IM1001") for sample data:

47

var incidentQuery; function findTypes( query ) { print( "Searching for incident records starting with " + query + "..." ); var incidentFile = new SCFile( "probsummary" ); var findIncident = incidentFile.doSelect( "number#\""+ query + "\"" ); if ( findIncident == RC_SUCCESS ) { print( "Success. Found incident records starting with " + query + ". The first record is:\n" + incidentFile ); var objectType = incidentFile.getType(); print( "The object incidentFile is of type: " + objectType ); var arrayField = incidentFile.action; print( "The contents of the action field are:\n" + arrayField ); fieldType = arrayField.getType(); print( "The type of the action field is: " + fieldType ); var textField = incidentFile.category; print( "The contents of the category field are:\n" + textField ); fieldType = textField.type; print( "The type of the category field is: " + fieldType ); } else { print( "Could not find incident records starting with " + query + ". " + RCtoString( findIncident ) ); return null; } } incidentQuery = "IM1001"; findTypes( incidentQuery );

SCFile.getXML()
This method returns an XML object representation of the current SCFile object. The XML object has the following format, which is compatible with the ServiceCenter Systems Web Services API: <model name="table" query="query"><keys><fieldname>key value</fieldname>...</keys> <instance><fieldname>instance value</fieldname>...</instance></model> The syntax for the method is getXML() No arguments are passed. The method returns an XML object containing the current SCFile object and a global return code value of RC_SUCCESS; or returns one of the error global return code values if the method cannot return an XML object. Example This example searches the contacts table for a contact name you define in the search variable, and displays the contact record as an XML object. This example requires the following sample data: A valid contact name (for example, "FALCON, JENNIFER") A invalid contact name (for example, "NOT A, CONTACT") var contactName; function findContact( name ) { print( "Searching for contact: " + name + "..." ); var contactList = new SCFile( "contacts" );

48

var isContact = contactList.doSelect( "contact.name=\""+ name + "\"" ) if ( isContact == RC_SUCCESS ) { print( "Success. found " + name + " in contact record:\n" + contactList.getXML() ); return contactList; } else { print( "Could not find contact. " + RCtoString( isContact ) ); return null; } } contactName = "FALCON, JENNIFER"; findContact( contactName ); contactName = "NOT A, CONTACT"; findContact( contactName );

SCFile.isRecord()
This is a deprecated method as of version 6.1 because it does not use the ServiceCenter-defined global return codes. This method, which requires using the deprecated File() object with a query or query condition, verifies that the query or query condition returns a ServiceCenter record. The syntax is isRecord(). No arguments are passed. The method returns a Boolean value of 1 if the File object contains a ServiceCenter record; or returns 0 if the method does not find a ServiceCenter record. Note: This method does not use the ServiceCenter-defined global return codes. Example This example searches the probsummary table for an incident record you define in the search variable, and displays the incident record object and the results of the isRecord() method. This example requires the following sample data: A valid incident record (for example, "IM1005") An invalid incident record (for example "incident") var incidentQuery; function findTypes( query ) { print( "Searching for incident records starting with " + query + "..." ); var incidentFile = new File( "probsummary", "number#\""+ query + "\"" ); if ( incidentFile != null ) { print( "Successfully allocated a File object"); if ( incidentFile.isRecord() ) { print( "Success. Found incident records starting with " + query + ". The first record is:\n" + incidentFile ); return incidentFile; } else { print( "Could not find incident records starting with " + query + "." ); return null; } } else { print( "Could not allocate a File object." );

49

return null; } } incidentQuery = "IM1005"; findTypes( incidentQuery ); incidentQuery = "incident"; findTypes( incidentQuery );

SCFile.join()
This method returns as a string the elements of either a ServiceCenter Datum array object or a JavaScript array. Note: This method does not use the ServiceCenter global return code values. The syntax is: join() No arguments are passed. Example This example does the following: Searches the probsummary table for any incident record you define in the search variable. Displays the new incident record as a text string. Displays the contents of the action field using the join() method. This example requires the following sample data: A valid value for the number field (for example, "IM1010") An Incident record with an action field value (for example, "IM1010") var incidentID; function findIncident( id ) { print( "Searching for Incident record: " + id + "..." ); var incidentFile = new SCFile( "probsummary" ); var rc = incidentFile.doSelect( "number=\"" + id + "\"" ); if ( rc == RC_SUCCESS ) { print( "Success. found Incident record:\n" + incidentFile.getText() ); print( "Displaying the contents of the action field as an object: " + incidentFile.action ); print( "Displaying the contents of the action field with join() method: " + incidentFile.action.join() ); return incidentFile; } else { print( "Could not find Incident record. " + RCtoString( rc ) ); return null; } } incidentID = "IM1010"; findIncident( incidentID );

SCFile.JSDate(dataType)
This method, which was deprecated as of version 6.1 with the introduction of the SCFile object, converts ServiceCenter date/time data into JavaScript date/time objects. The SCFile object now

50

automatically converts ServiceCenter date/time data into JavaScript date/time objects. Alternatively, you can now use the XMLDate object and its methods to convert between date/time formats. The syntax is: JSDate( dataType ) This method does not have any return values. The following argument is valid for this method:
Argument dataType Data type String Description Specifies the data type of a field in a SCFile object.

Example This example does the following: Searches the probsummary table for any incident record you define in the search variable. Displays the incident record and the value of the open.time field. Creates an SCDatum object containing the number of milliseconds you want to convert. Converts the open.time field into an SCDatum object. (By default the open.time field data is in the ServiceCenter date/time data type.) Converts the SCDatum object into a JavaScript date/time object. This example requires a valid incident record with a value in the open.time field (for example, "IM1010") as sample data: var incidentID; function findIncident( id ) { print( "Searching for incident: " + id + "..." ); var incidentFile = new SCFile( "probsummary" ); var f = incidentFile.doSelect( "number=\""+ id + "\"" ); if ( f == RC_SUCCESS ) { print( "Success. found " + id + " in incident record:\n" + incidentFile.getText() ); print( "The value of the open.time field is: " + incidentFile.open_time ); print( "Converting open.time to an SCDatum object..." ); var dat = new SCDatum( incidentFile.open_time ); print( "The new SCDatum object is: " + dat ); print( "Converting the SCDatum object to a JSDate..." ); var j = dat.JSDate(); print( "The converted SCDatum object is: " + j ); return incidentFile; } else { print( "Could not find incident record. " + RCtoString( f ) ); return null; } } incidentID = "IM1010"; findIncident( incidentID );

SCFile.length()
This method returns the number of array elements in an array stored in a ServiceCenter Datum object. You can use this method to return the length of ServiceCenter array fields, which are always stored as Datum objects. To query a particular array field in an SCFile object, you can use the following format:

51

SCFile_object.array_field_name.length() Replace any periods in the name of array_field_name with underscores. For example, convert the ServiceCenter array field update.action to update_action when querying it from JavaScript. The syntax for the method is array_field_name.length() No arguments are passed. The method returns the number of array elements in an array stored in a ServiceCenter Datum object and a global return code value of RC_SUCCESS; or returns one of the error global return code values if the method cannot return the number of array elements. Example This example does the following: Searches the probsummary table for any incident record you define in the search variable. Attempts to get the size of the returned SCFile object (the result is always zero). Displays the contents of the action field (the action field contains ServiceCenter array data). Displays the size of the action field using the ServiceCenter length() method. Converts the SCFile object into a JavaScript array using the ServiceCenter toArray() method. Displays the size of the new JavaScript array using the core JavaScript length property. var incidentQuery; function findIncidents( query ) { print( "Searching for incident records starting with " + query + "..." ); var incidentFile = new SCFile( "probsummary" ); var findIncident = incidentFile.doSelect( "number#\""+ query + "\"" ); if ( findIncident == RC_SUCCESS ) { print( "Success. Found incident records starting with " + query + ". The first record is:\n" + incidentFile ); var objectSize = incidentFile.getSize(); print( "Running the getSize() method on the returned SCFile object produces the following result: " + objectSize ); var actionText = incidentFile.action; print( "The contents of the action field is:\n" + actionText ); var actionSize = incidentFile.action.getSize(); print( "The size of the action field is: " + actionSize ); print( "Converting the SCFile object to a JavaScript array.." ); var incidentArray = incidentFile.toArray(); print( "The new JavaScript array is:\n" + incidentArray ); var arraySize = incidentArray.length; print( "The size of the converted array is: " + arraySize ); return incidentFile; } else { print( "Could not find incident records starting with " + query + ". " + RCtoString( findIncident ) ); return null; } } incidentQuery = "IM1005"; findIncidents( incidentQuery );

52

SCFile.pop()
This method removes the last element from a JavaScript array and returns the element removed as a string. The syntax for the method is pop() No arguments are passed. Note: This method does not use the ServiceCenter global return code values. Example This example does the following: Searches the probsummary table for any incident record you define in the search variable. Displays the new incident record as a text string. Converts the action field into a JavaScript array. Adds an item to the end of the array and displays the total number of elements in the array. Removes an item from the end of the array and displays the array item removed This example requires the following sample data: A valid value for the number field (for example, "IM1010") An Incident record with an action field value (for example, "IM1010") var incidentID; function findIncident( id ) { print( "Searching for Incident record: " + id + "..." ); var incidentFile = new SCFile( "probsummary" ); var rc = incidentFile.doSelect( "number=\"" + id + "\"" ) if ( rc == RC_SUCCESS ) { print( "Success. found Incident record:\n" + incidentFile.getText() ); print( "Converting the action field to a JavaScript array..." ); var a = incidentFile.action.toArray(); print( "The action field array contains the following: " + a ); print( "Pushing new array entry..." ); var addOne = a.push( "First array item" ); print( "The number of items in the array are: " + addOne ); print( "The action field array contains the following: " + a ); print( "Popping new array entry..." ); var removeOne = a.pop(); print( "The array item removed was: " + removeOne ); print( "The action field array contains the following: " + a ); return incidentFile; } else { print( "Could not find Incident record. " + RCtoString( rc ) ); return null; } } incidentID = "IM1010"; findIncident( incidentID );

SCFile.push(arrayItem)
This method adds an entry to the end of a JavaScript array and returns the total number of entries in the array. If you apply this method to a ServiceCenter array object, then it adds the item but does not return the number of entries in the array.

53

Note: This method does not use the ServiceCenter global return code values. The syntax is: push( arrayItem ) The following argument is valid for this method:
Argument arrayItem Data type String Description Specifies the array item you want to add to a JavaScript array.

Example This example does the following: Searches the probsummary table for any incident record you define in the search variable. Displays the new incident record as a text string. Converts the contents of the action field into a JavaScript array. Adds an item to the end of the JavaScript array and prints the total number of items in the array. This example requires the following sample data: A valid value for the number field (for example, "IM1010") An Incident record with an action field value (for example, "IM1010") var incidentID; function findIncident( id ) { print( "Searching for Incident record: " + id + "..." ); var incidentFile = new SCFile( "probsummary" ); var rc = incidentFile.doSelect( "number=\"" + id + "\"" ); if ( rc == RC_SUCCESS ) { print( "Success. found Incident record:\n" + incidentFile.getText() ); print( "Converting the action field to a JavaScript array..." ); var a = incidentFile.action.toArray(); print( "The action field array contains the following: " + a ); print( "Pushing new array entry..." ); var addOne = a.push( "First array item" ); print( "The number of items in the array are: " + addOne ); print( "The action field array contains the following: " + a ); print( "Pushing new array entry..." ); var addTwo = a.push( "Second array item" ); print( "The number of items in the array are: " + addTwo ); print( "The action field array contains the following: " + a ); return incidentFile; } else { print( "Could not find Incident record. " + RCtoString( rc ) ); return null; } } incidentID = "IM1010"; findIncident( incidentID );

SCFile.setType(dataType)
This method. which was deprecated as of version 6.1 with the introduction of the SCFile object, sets the data type of ServiceCenter datum objects. The SCFile object now automatically converts ServiceCenter data types into a corresponding JavaScript data types. You can also use the XMLDate object and its methods to convert between date/time formats. The syntax is setType( dataType ). The following argument is valid for this method:

54

Argument dataType

Data type Number

Description The objects ServiceCenter data type. See the list of ServiceCenter data types.

Example This example does the following: Creates an SCDatum object containing the number of milliseconds you want to convert. Sets the data type of the SCDatum object to a ServiceCenter date/time type. Converts the number of milliseconds into a JavaScript date/time. This example requires a number of milliseconds (for example, "1234567890") as sample data: var millisecs; function findDateTime( num ) { var t = new SCDatum( num ); t.setType( 3 ); print( num + " milliseconds is equal to the date: " + t.JSDate() ); } millisecs = 1234567890; findDateTime( millisecs );

SCFile.setValue(newValue)
This method adds or updates a ServiceCenter record with a specified new field value. Note: This method does not use the ServiceCenter global return codes and does not return any value. The syntax is setValue( newValue ). The following argument is valid for this method:
Argument newValue Data type String Description Specifies the new value for the ServiceCenter object Precede special characters such as quotation marks with a backslash (\), which acts as an escape character..

Example This example does the following: Searches the probsummary table for any incident record you define in the search variable. Displays the current value of the action field. Sets the value of the action field to any value you define in the input variable. This example requires the following sample data: A valid incident record with a value in the action field (for example, "IM1010") A valid action field value update (for example, set the action field to "New description") var incidentID; var newValue; function findIncident( id, value ) { print( "Searching for Incident record: " + id + "..." ); var incidentFile = new SCFile( "probsummary" ); var rc = incidentFile.doSelect( "number=\"" + id + "\"" ); if ( rc == RC_SUCCESS ) { print( "Success. found Incident record " + id ); print( "Displaying the contents of the action field as an object: " + incidentFile.action ); print( "Setting the value of the action field..." );

55

incidentFile.action.setValue( value ); print( "Displaying the contents of the site field as an object: " + incidentFile.action ); print( "Displaying the Incident record: " + incidentFile ); return incidentFile; } else { print( "Could not find Incident record. " + RCtoString( rc ) ); return null; } } incidentID = "IM1010"; newValue = "New description"; findIncident( incidentID, newValue );

SCFile.shift()
This method removes the first element from a JavaScript array and returns the removed element as a string. Note: This method does not use the ServiceCenter global return code values. The syntax is: shift() No arguments are passed. Example This example does the following: Searches the probsummary table for any incident record you define in the search variable. Displays the new incident record as a text string. Converts the action field into a JavaScript array. Adds an item to the end of the array and displays the total number of elements in the array. Removes an item from the beginning of the array and displays the array item removed. This example requires the following sample data: A valid value for the number field (for example, "IM1010") An Incident record with an action field value (for example, "IM1010") var incidentID; function findIncident( id ) { print( "Searching for Incident record: " + id + "..." ); var incidentFile = new SCFile( "probsummary" ); var rc = incidentFile.doSelect( "number=\"" + id + "\"" ); if ( rc == RC_SUCCESS ) { print( "Success. found Incident record:\n" + incidentFile.getText() ); print( "Converting the action field to a JavaScript array..." ); var a = incidentFile.action.toArray(); print( "The action field array contains the following: " + a ); print( "Pushing new array entry..." ); var addOne = a.push( "First array item" ); print( "The number of items in the array are: " + addOne ); print( "The action field array contains the following: " + a ); print( "Shifting array one entry..." ); var removeOne = a.shift(); print( "The array item removed was: " + removeOne ); print( "The action field array contains the following: " + a );

56

return incidentFile; } else { print( "Could not find Incident record. " + RCtoString( rc ) ); return null; } } incidentID = "IM1010"; findIncident( incidentID );

SCFile.toArray()
This method converts a ServiceCenter Datum object into a JavaScript array. The syntax for this method is: toArray() No arguments are passed. It returns either a JavaScript array and RC_SUCCESS; or one of the other global return code values. Example This example does the following: Searches the probsummary table for any Incident record you define in the search variable. Displays the Incident record as a text string. Converts the contents of the action field into a JavaScript array. This example requires the following sample data: A valid Incident record number (for example, "IM1010") An Incident record with an action field value (for example, "IM1010") var incidentID; function findIncident( id ) { print( "Searching for Incident record: " + id + "..." ); var incidentFile = new SCFile( "probsummary" ); var rc = incidentFile.doSelect( "number=\"" + id + "\"" ); if ( rc == RC_SUCCESS ) { print( "Success. found Incident record:\n" + incidentFile.getText() ); print( "Converting the action field to a JavaScript array..." ); var a = incidentFile.action.toArray(); print( "The action field contains the following " + a ); return incidentFile; } else { print( "Could not find Incident record. " + RCtoString( rc ) ); return null; } } incidentID = "IM1010"; findIncident( incidentID );

57

SCFile.unshift(arrayItem)
This method adds an entry to the beginning of a JavaScript array and returns the total number of entries in the array. If you apply this method to a ServiceCenter array object, then it adds the item but does not return the number of entries in the array. Note: This method does not use the ServiceCenter global return code values. The syntax for this method is unshift( arrayItem ) The following argument is valid for this method:
Argument arrayItem Data type String Description Specifies the array item you want to add to a JavaScript array.

Example This example does the following: Searches the probsummary table for any incident record you define in the search variable. Displays the new incident record as a text string. Converts the contents of the action field into a JavaScript array. Adds an item to the beginning of the JavaScript array and prints the total number of items in the array. This example requires the following sample data: A valid value for the number field (for example, "IM1010") An Incident record with an action field value (for example, "IM1010") var incidentID; function findIncident( id ) { print( "Searching for Incident record: " + id + "..." ); var incidentFile = new SCFile( "probsummary" ); var rc = incidentFile.doSelect( "number=\"" + id + "\"" ) if ( rc == RC_SUCCESS ) { print( "Success. found Incident record:\n" + incidentFile.getText() ); print( "Converting the action field to a JavaScript array..." ); var a = incidentFile.action.toArray(); print( "The action field array contains the following: " + a ); print( "Unshifting array one entry..." ); var unshifting = a.unshift( "First array item" ); print( "The number of items in the array are: " + unshifting ); print( "The action field array contains the following: " + a ); return incidentFile; } else { print( "Could not find Incident record. " + RCtoString( rc ) ); return null; } } incidentID = "IM1010"; findIncident( incidentID );

58

JavaScript methods for the XML object


XML.addAttribute(AttributeName, AttributeValue)
This method inserts an attribute and an attribute value into the current element. It returns an XML object containing the updated element; or returns null if the method cannot add the attribute. Use the XMLgetxxx methods to navigate through an XML document. The syntax is: addAttribute( AttributeName, AttributeValue ) The following arguments are valid for this method:
Argument AttributeName Data type String Description Specifies the text string you want the script to use as the XML attribute name. Must contain characters valid for an XML element (for example, the string cannot include the characters < or >). Specifies the text string you want the script to use as the XML attribute value. Must contain characters valid for an XML element (for example, the string cannot include the characters < or >).

AttributeValue

String

Example This example adds a new attribute and an attribute value to an element you select from an XML document. This example requires a local XML file, such as a file called C:\test02.xml containing the following sample data: "<document><parent1>value1</parent1><parent2></parent2></document>" /* * * * * Create variables to store XML objects and strings. Use XMLObject to store a valid XML object such as an XML file. Use sourceXMLString to store a valid XML string. The script sets the content of XMLString to sourceXMLString. The script assigns values to the empty variables later on */

var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test02.xml", true ); var XMLSource; var TargetNode; var searchResults; var printResults; var AttributeName; var AttributeValue; /* * * * * * Create a function that searches an XML object (node) for a particular element (targetElem) and returns an XML object containing the element. This fuction assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data it only returns the first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) {

59

return null; } childNode = node.getNextSiblingElement(); } node = childNode; } else { node = childNode; } } return node; } /* Create a function to print the target element and search results */ function createNewAttribute( searchResult, targetNode, attrName, attrValue ) { print( "The target element we are looking for is: " + targetNode ); if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); print( "Adding new attribute " + attrName + " to element " + elementName ); searchResult.addAttribute( attrName, attrValue ); print( "The new object is:\n" + searchResult ); return searchResult; } else { print( "Cannot find " + target ); return null; } } /* Set variable values for XMLFile and TargetNode. Run functions. print( "Processing XML from XMLFile... \n" ); TargetNode = "parent1"; XMLSource = XMLFile; searchResults = findTargetElement( XMLSource, TargetNode ); AttributeName = "id"; AttributeValue = "test"; createNewAttribute( searchResults, TargetNode, AttributeName, AttributeValue ); */

XML.addElement(String)
This method inserts an XML element as a child of the current element. It returns an XML object containing the new XML element; or returns null if the method cannot add the element. Use the XML.getxxx methods to navigate through an XML document. The syntax for this method is: addElement( String ) The following argument is valid:
Argument String Data type String Description Specifies the text string you want the script to use as the XML element name. Must contain characters valid for an XML element (for example, the string cannot include the characters < or >).

60

Example This example adds a child element to any element you select in an XML document. It requires a local XML file, such as a file called C:\test02.xml containing the following sample data: "<document><parent1>value1</parent1><parent2></parent2></document>" /* * * * * Create variables to store XML objects and strings. Use XMLObject to store a valid XML object such as an XML file. Use sourceXMLString to store a valid XML string. The script sets the content of XMLString to sourceXMLString. The script assigns values to the empty variables later on */

var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test02.xml", true ); var XMLSource; var TargetNode; var searchResults; var printResults; var NewNodeName; /* * * * * * Create a function that searches an XML object (node) for a particular element (targetElem) and returns an XML object containing the element. This fuction assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data it only returns the first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement(); } node = childNode; } else { node = childNode; } } return node; } /* Create a function to print the target element and search results */ function createNewNode( searchResult, targetNode, nodeName ) { print( "The target element we are looking for is: " + targetNode ); if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); print( "Adding new node " + nodeName + " to element " + elementName ); var newNode = searchResult.addElement( nodeName ); print( "The new object is:\n" + searchResult ); return searchResult;

61

} else { print( "Cannot find " + target ); return null; } } /* Set variable values for XMLFile and TargetNode. Run functions. print( "Processing XML from XMLFile... \n" ); TargetNode = "parent1"; XMLSource = XMLFile; searchResults = findTargetElement( XMLSource, TargetNode ); NewNodeName = "child8"; createNewNode( searchResults, TargetNode, NewNodeName ); */

XML.appendNode(name)
This method inserts an XML node into an XML object. It returns an XML object containing the new XML node; or returns null if the method cannot append the node to the current target node. This method requires an existing XML object with a document element, but it does not update the existing XML object. The syntax is appendNode( name ) The following argument is valid for this method:
Argument name Data type String Description Specifies the XML node name you want to append to the target XML object. Must contain characters valid for XML (for example, the string cannot include the characters < or > except as XML entities such as &lt; and &gt;).

Example This example appends an XML node to an XML source object. It requires an XML object containing sample data such as: "<document> </document>" var XMLObject = new XML; var NewNodeName; var NewNodeValue; var NewNodeType; var TargetNode; XMLObject = XMLObject.setContent( "<document> </document>" ); function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement(); } node = childNode; } else {

62

node = childNode; } } return node; } function appendNewNode( type, name, value, xmlSource, target ) { print( "The XML source object is: " + xmlSource); print( "Creating node of type: " + type + " named: " + name + " with value: " + value ); var NewNode = xmlSource.createNode( type, name, value ); print( "Appending " + NewNode.toXMLString() + " to: " + target ); var FoundNode = findTargetElement( xmlSource, target ); var appendedNode = FoundNode.appendNode( NewNode ); print( "The new XML object is: " + xmlSource ); } NewNodeType = 1; NewNodeName = "node"; NewNodeValue = "test"; TargetNode = "document"; appendNewNode( NewNodeType, NewNodeName, NewNodeValue, XMLObject, TargetNode );

XML.createNode(type, name, value)


This method creates an XML node from an XML object. It returns an XML object containing the new XML node; or returns null if the method cannot create the node. This method requires an existing XML object with a document element, but does not update the object. The syntax is: createNode( type, name, value ) The following arguments are valid for this method:
Argument type Data type Integer Description Specifies the XML DOM node type for the node you want the script to create. This method accepts only XML DOM types 1, 2, and 3. See the W3C Web site for a complete listing of XML DOM node-types by integer. Specifies the text string you want the script to add as the XML node name. Must contain characters valid for XML (for example, the string cannot include the characters < or > except as XML entities such as &lt; and &gt;). Specifies the text string you want the script to add as the XML node value. Must contain characters valid for XML (for example, the string cannot include the characters < or > except as XML entities such as &lt; and &gt;).

name

String

value

String

Example This example creates an XML node from an XML source object. It requires as sample data an XML object, such as an object containing: "<document> </document>" var XMLObject = new XML; var NewNodeName; var NewNodeValue; var NewNodeType; XMLObject = XMLObject.setContent( "<document> </document>" ); function createNewNode( type, name, value, xmlSource ) { print( "The XML source object is: " + xmlSource); print( "Creating node of type: " + type + " named: " + name + " with value: " + value ); var NewNode = xmlSource.createNode( type, name, value ); print( "The XML source object remains unchanged: " + XMLObject ); print( "The new node converted to an XML string is: " +

63

NewNode.toXMLString() ); print( "Applying the getName method to the new node produces: " + NewNode.getName() ); print( "Applying the getValue method on the new node produces: " + NewNode.getValue() ); } NewNodeType = 1; NewNodeName = "node"; NewNodeValue = "test"; createNewNode( NewNodeType, NewNodeName, NewNodeValue, XMLObject ); NewNodeType = 2; NewNodeName = "id"; NewNodeValue = "test"; createNewNode( NewNodeType, NewNodeName, NewNodeValue, XMLObject ); NewNodeType = 3; NewNodeName = null; NewNodeValue = "Text node"; createNewNode( NewNodeType, NewNodeName, NewNodeValue, XMLObject );

XML.getAttributeNode(Attribute)
This method returns an XML object containing the target attribute the current element; or returns null if the method cannot find the target attribute in the current element. Use the other XML.getxxx methods to navigate through an XML document. The syntax is: getAttributeNode( Attribute ) The following argument is valid for this method:
Argument Attribute Data type String Description Specifies the XML attribute you want the script to return.

Example This example searches for a particular attribute of any given element in an XML document. It requires a local XML file, such as a file called C:\test.xml containing the following sample data: "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2> <child3 /><child4 /></parent2></document>" /* Create variables to store XML objects and strings. * Use XMLFile to store a valid XML file. * The script assigns values to the empty variables later on */ var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test.xml", true ); var XMLSource; var TargetNode; var TargetAttribute; var searchResults; /* * * * * * Create a function that searches an XML object (node) for a particular element (targetElem) and returns an XML object containing the element. This fuction assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data, it only returns the first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement();

64

if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement(); } node = childNode; } else { node = childNode; } } return node; } /* Create a function to print the target element and search results */ function printFindResults( target, searchResult, attribute ) { print( "The target element we are looking for is: " + target ); if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); var attributeFound = findAttributeNode( searchResult, attribute ); return attributeFound; } else { print( "Cannot find " + target ); return null; } } /* Create a function to find the attribute node of the target element */ function findAttributeNode( sourceObject, attribute ) { print( "Looking for attribute node " + attribute ); var attributeNode = sourceObject.getAttributeNode( attribute ); if ( attributeNode != null ) { print( "Success. Found attribute " + attributeNode ); return attributeNode; } else { print( "Fail. Did not find attribute " + attribute ); return null; } } /* Set variable values for XMLFile and TargetNode. Run functions print( "Processing XML from XMLFile... \n" ); TargetNode = "child1"; XMLSource = XMLFile; TargetAttribute = "attribute1"; searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( TargetNode, searchResults, TargetAttribute ); */

65

XML.getAttributeValue(Attribute)
This method returns the string value of the target attribute; or returns null if the method cannot find an attribute value. Use the other XML.getxxx methods to navigate through an XML document. The syntax is: getAttributeValue( Attribute ) The following argument is valid for this method:
Argument Attribute Data type String Description Specifies the XML attribute whose value you want the script to return.

Example This example searches for the attribute value of any given element in an XML document. It requires as sample data a local XML file, such as a file called C:\test.xml containing: "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2> <child3 /><child4 /></parent2></document>" /* Create variables to store XML objects and strings. * Use XMLFile to store a valid XML file. * The script assigns values to the empty variables later on */ var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test.xml", true ); var XMLSource; var TargetNode; var TargetAttribute; var searchResults; /* * * * * * Create a function that searches an XML object (node) for a particular element (targetElem) and returns an XML object containing the element. This fuction assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data it only returns the first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement(); } node = childNode; } else { node = childNode; } } return node; } /* Create a function to print the target element and search results */

66

function printFindResults( target, searchResult, attribute ) { print( "The target element we are looking for is: " + target ); if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); var attributeFound = findAttributeValue( searchResult, attribute ); return attributeFound; } else { print( "Cannot find " + target ); return null; } } /* Create a function to find the attribute node of the target element */ function findAttributeValue( sourceObject, attribute ) { print( "Looking for attribute value of " + attribute ); var attributeValue = sourceObject.getAttributeValue( attribute ); if ( attributeValue != null ) { print( "Success. The value of " + attribute + " is " + attributeValue ); return attributeValue; } else { print( "Fail. Did not find attribute " + attribute ); return null; } } /* Set variable values for XMLFile and TargetNode. Run functions print( "Processing XML from XMLFile... \n" ); TargetNode = "child1"; XMLSource = XMLFile; TargetAttribute = "attribute1"; searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( TargetNode, searchResults, TargetAttribute ); */

XML.getDocumentElement()
This method searches an XML object for the DOM document element (or "root" node). If successful, it returns an XML object containing the document element and all of its child elements. It returns null if applied to an empty or invalid XML object. Important: You cannot use this method on objects that you have converted using the toXMLString() method. The syntax is getDocumentElement() No arguments are passed. Example This example displays the XML document element from four different input sources. It requires the following sample data: A valid XML object, such as the list of currently logged on users stored in system.users A valid XML string, such as: "<document><parent1><child1 attribute1=\"1\" /></parent1><parent2 /></document>"

67

A non-compliant XML string, such as: "<document1><parent1 /></document1><document2><parent2 /></document2>" An empty XML object /* * * * * * * * * Create variables to store XML objects and strings. Use goodXML to store a valid XML string. Use badXML to store any erroneous XML string, in this case a second document * element. Use xmlObject to store a valid XML object such as the system.users list. The script sets the content of xmlString to goodXML; the content of xmlBad to badXML; and the content of xmlEmpty to an XML object*/

var goodXML = "<document><parent1><child1 attribute1=\"1\" /></parent1><parent2 /></document>"; var badXML = "<document1><parent1 /></document1><document2><parent2 /></document2>"; var xmlObject = system.users; var xmlString = new XML(); xmlString = xmlString.setContent( goodXML ); var xmlBad = new XML(); xmlBad = xmlBad.setContent( badXML ); print( "The value of xmlBad is:\n" + xmlBad ); var xmlEmpty = new XML(); /* Create a function to execute the getDocumentElement method on the document argument. */ function getDocElem( document ) { var DocElem = document.getDocumentElement(); if ( DocElem != null ) { var DocElemName = DocElem.getNodeName(); print( "Success. Found the document element " + the following object: \n" + document ); return DocElem; } else { print( "Error. Did not find document element in object: \n" + document ); return null; } } /* Run the getDocElem and getDocElemName functions on * input sources. Print the objects returned by each print( "Now searching for ); getDocElem( xmlObject ); print( "Now searching for ); getDocElem( xmlString ); print( "Now searching for string...\n" ); getDocElem( xmlBad ); print( "Now searching for ); getDocElem( xmlEmpty );

DocElemName + " in

the following

four function. */

a document element in a valid XML object...\n" a document element in a valid XML string...\n" a document element in a non-compliant XML a document element in an empty XML object...\n"

XML.getFirstAttribute(Element)
The method returns an object representing the first attribute of the current node or returns null if the XML object has no attributes.

68

The syntax is getFirstAttribute(); or getFirstAttribute(Element). The following argument is valid for this method:
Argument Element Data type String Description Contains the name of the element you want the method to use as the starting position when searching for the first attribute.

Example This example displays the first attribute of any element you select. It allows you to select an element from two different input sources. It requires the following sample data: A local XML file, such as a file called C:\test.xml containing the following sample data: "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2> <child3 /><child4 /></parent2></document>" A valid XML string, such as: "<document><parent1><child1 /><child2 attribute2=\"b\" /></parent1> <parent2 /></document>" /* * * * * Create variables to store XML objects and strings. Use XMLObject to store a valid XML object such as an XML file. Use sourceXMLString to store a valid XML string. The script sets the content of XMLString to sourceXMLString. The script assigns values to the empty variables later on */

var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test.xml", true ); var sourceXMLString = "<document><parent1><child1 /><child2 attribute2=\"b\" /></parent1><parent2 /></document>"; var XMLString = new XML(); XMLString = XMLString.setContent( sourceXMLString ); var XMLSource; var TargetNode; var searchResults; var attributeResults; /* Create a function that searches an XML object (node) for a * particular element (targetElem) and returns an XML object * containing the element. * * * This function assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data it only returns the first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement(); } node = childNode; } else {

69

node = childNode; } } return node; } /* Create a function to print the target element and search results */ function printFindResults( target, searchResult ) { if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); return searchResult; } else { print( "Cannot find " + target ); return null; } } /* Create a function to find the first attribute of the target element */ function findFirstAttribute( sourceObject, targetNode ) { var startingNode = findTargetElement( sourceObject, targetNode ) var attribute = startingNode.getFirstAttribute(); if ( attribute != null ) { return attribute; } else { return null; } } /* Create function to print the 1st attribute of the target element */ function printAttributeResults( target, searchResult ) { if ( searchResult != null ) { var attributeName = searchResult.getNodeName(); print( "The first attribute of " + target + " is: " + attributeName ); } else { print( "There are no attributes of " + target ); } } /* Set variable values for XMLFile and TargetNode. Run functions */ print( "Processing XML from XMLFile... \n" ); TargetNode = "child1"; XMLSource = XMLFile; print( "The target element we are looking for is: " + TargetNode ); searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( TargetNode, searchResults ); attributeResults = findFirstAttribute( XMLSource, TargetNode ); printAttributeResults( TargetNode, attributeResults ); /* Set variable values for XMLFile and TargetNode. Run functions */ print( "Processing XML from XMLString... \n" ); TargetNode = "child2"; XMLSource = XMLString; print( "The target element we are looking for is: " + TargetNode ); searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( TargetNode, searchResults ); attributeResults = findFirstAttribute( XMLSource, TargetNode ); printAttributeResults( TargetNode, attributeResults );

70

XML.getFirstChildElement(Element)
The method returns an object representing the first child node of the current node; or returns null if the XML object has no child node. The syntax is: getFirstChildElement() Or getFirstChildElement(Element). The following argument is valid for this method:
Argument Element Data type String Description Contains the name of the element you want the method to use as the starting position when searching for the first child element.

Example This example displays the first child element of any element you select. It allows you to select an element from two different input sources. It requires the following sample data: A local XML file, such as a file called C:\test.xml containing the following sample data: "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2> <child3 /><child4 /></parent2></document>" A valid XML string, such as: "<document><parent1><child1 /><child2 attribute2=\"b\" /></parent1> <parent2 /></document>" /* * * * * Create variables to store XML objects and strings. Use XMLObject to store a valid XML object such as an XML file. Use sourceXMLString to store a valid XML string. The script sets the content of XMLString to sourceXMLString. The script assigns values to the empty variables later on */

var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test.xml", true ); var sourceXMLString = "<document><parent1><child1 /><child2 attribute2=\"b\" /></parent1><parent2 /></document>"; var XMLString = new XML(); XMLString = XMLString.setContent( sourceXMLString ); var XMLSource; var TargetNode; var searchResults; var childResults; /* * * * * * * Create a function that searches an XML object (node) for a particular element (targetElem) and returns an XML object containing the element. This function assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data, it returns only the first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null)

71

{ node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement(); } node = childNode; } else { node = childNode; } } return node; } /* Create a function to print the target element and search results */ function printFindResults( target, searchResult ) { if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); return searchResult; } else { print( "Cannot find " + target ); return null; } } /* Create a function to find the first child element of the target * element */ function findFirstChild( sourceObject, targetNode ) { var startingNode = findTargetElement( sourceObject, targetNode ); var firstChild = startingNode.getFirstChildElement(); if ( firstChild != null ) { return firstChild; } else { return null; } } /* Create a function to print the first child element of the * target element.*/ function printChildResults( target, searchResult ) { if ( searchResult != null ) { var childName = searchResult.getNodeName(); print( "The first child element of " + target + " is: " + childName ); } else { print( "There are no child elements of " + target ); } } /* Set variable values for XMLFile and TargetNode. Run functions */ print( "Processing XML from XMLFile... \n" );

72

TargetNode = "parent1"; XMLSource = XMLFile; print( "The target element we are looking for is: " + TargetNode ); searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( TargetNode, searchResults ); childResults = findFirstChild( XMLSource, TargetNode ); printChildResults( TargetNode, childResults ); /* Set variable values for XMLFile and TargetNode. Run functions */

print( "Processing XML from XMLString... \n" ); TargetNode = "parent2"; XMLSource = XMLString; print( "The target element we are looking for is: " + TargetNode ); searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( TargetNode, searchResults ); childResults = findFirstChild( XMLSource, TargetNode ); printChildResults( TargetNode, childResults );

XML.getName()
The method, which is a synonym for getNodeName(), returns a string representing the name of the current element or attribute; or returns null if the current node has no name. Use the other XML.getxxx methods to navigate through an XML document. The syntax is: getName() No arguments are passed. Example This example displays the names of the elements and attributes in an XML document. It requires the following sample data: A local XML file, such as a file called C:\test.xml containing the following sample data: "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2> <child3 /><child4 /></parent2></document>" A valid XML string, such as: "<document><parent1><child1>0123</child1></parent1></document>" /* * * * * Create variables to store XML objects and strings. Use XMLObject to store a valid XML object such as an XML file. Use sourceXMLString to store a valid XML string. The script sets the content of XMLString to sourceXMLString. The script assigns values to the empty variables later on */

var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test.xml", true ); var sourceXMLString = "<document><parent1><child1>0123</child1></parent1></document>"; var XMLString = new XML(); XMLString = XMLString.setContent( sourceXMLString ); var XMLSource; function walkXML( elem ) { print( "Element " + elem.getName() ); var node = elem.getFirstAttribute(); while( node != null ) { var attrName = node.getName(); var attrValue = node.getNodeValue(); print( "Attribute " + attrName + " = " + attrValue ); node = elem.getNextAttribute();

73

} var nodeValue = elem.getNodeValue(); if ( typeof nodeValue == "string" && nodeValue.length > 0 ) { print( "Element value of " + elem.getName() + " is: " + nodeValue ); } var child = elem.getFirstChildElement(); while( child != null ) { var nodeName = child.getName(); var nodeValue = child.getNodeValue(); walkXML( child ); child = child.getNextSiblingElement(); } } print( "Now printing the structure of an XML file...\n" ); XMLSource = XMLFile; walkXML( XMLSource ); print( "Now printing the structure of an XML string...\n" ); XMLSource = XMLString; walkXML( XMLSource );

XML.getNextAttribute(Element)
The method returns an object representing the first attribute of the current node; or returns null if the XML object has no attributes. The syntax is either getNextAttribute() without arguments, or getNextAttribute(Element). The following argument is valid for this method:
Argument Element Data type String Description Contains the name of the element you want the method to use as the starting position when searching for the first attribute.

Example This example displays the first attribute of any element you select. It allows you to select an element from two different input sources. It requires the following sample data: A local XML file, such as a file called C:\test.xml containing the following sample data: "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2> <child3 /><child4 /></parent2></document>" A valid XML string, such as: "<document><parent1><child1 /> <child2 attribute2=\"b\" attribute3=\"c\" /></parent1><parent2 /></document>" /* * * * * Create variables to store XML objects and strings. Use XMLObject to store a valid XML object such as an XML file. Use sourceXMLString to store a valid XML string. The script sets the content of XMLString to sourceXMLString. The script assigns values to the empty variables later on */

var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test.xml", true ); var sourceXMLString = "<document><parent1><child1 /><child2 attribute2=\"b\" attribute3=\"c\" /></parent1><parent2 /></document>"; var XMLString = new XML(); XMLString = XMLString.setContent( sourceXMLString ); var XMLSource; var TargetNode; var searchResults;

74

var attributeResults; /* * * * * * Create a function that searches an XML object (node) for a particular element (targetElem) and returns an XML object containing the element. This function assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data, it returns onlythe first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null;; } childNode = node.getNextSiblingElement(); } node = childNode; } else { node = childNode; } } return node; } /* Create a function to print the target element and search results */ function printFindResults( target, searchResult ) { if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); return searchResult; } else { print( "Cannot find " + target ); return null; } } /* Create a function to find the first attribute of the target element */ function findFirstAttribute( sourceObject, targetNode ) { var startingNode = findTargetElement( sourceObject, targetNode ); var firstAttribute = startingNode.getFirstAttribute(); if ( firstAttribute != null ) { return firstAttribute; } else { return null; } } /* Create a function to print the first attribute of the target element */

75

function printAttributeResults( target, searchResult ) { if ( searchResult != null ) { var attributeName = searchResult.getNodeName(); print( "The first attribute of " + target + " is: " + attributeName ); return searchResult; } else { print( "There are no attributes of " + target ); return null; } } /* Create a function to find the next attribute of the target element */ function findNextAttribute( sourceObject, targetNode ) { var startingNode = findTargetElement( sourceObject, targetNode ); var firstAttribute = startingNode.getFirstAttribute(); if ( firstAttribute != null ) { var nextAttribute = startingNode.getNextAttribute(); while ( nextAttribute != null ) { var attributeName = nextAttribute.getNodeName(); print( "The next attribute of " + targetNode + " is: " + attributeName ); nextAttribute = nextAttribute.getNextAttribute(); } print( "There are no more attributes of " + targetNode ); return targetNode; } else { return null; } } /* Set variable values for XMLFile and TargetNode. Run functions */

print( "Processing XML from XMLFile... \n" ); TargetNode = "child1"; XMLSource = XMLFile; print( "The target element we are looking for is: " + TargetNode ); searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( TargetNode, searchResults ); attributeResults = findFirstAttribute( XMLSource, TargetNode ); printAttributeResults( TargetNode, attributeResults ); findNextAttribute( XMLSource, TargetNode ); /* Set variable values for XMLFile and TargetNode. Run functions */

print( "Processing XML from XMLString... \n" ); TargetNode = "child2"; XMLSource = XMLString; print( "The target element we are looking for is: " + TargetNode ); searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( TargetNode, searchResults ); attributeResults = findFirstAttribute( XMLSource, TargetNode ); printAttributeResults( TargetNode, attributeResults ); findNextAttribute( XMLSource, TargetNode );

XML.getNextSiblingElement(Element)
The method returns an object representing the next node at the same level in the Document Object Model (DOM) tree as the current node; or returns null if the XML object has no sibling node. The syntax is either:

76

getNextSiblingElement() Or getNextSiblingElement(Element). The following argument is valid for this method:


Argument Element Data type String Description Contains the name of the element you want the method to use as the starting position when searching for the next sibling element.

Example This example displays the next sibling element of any element you select. It allows you to select an element from two different input sources. It requires the following sample data: A local XML file, such as a file called C:\test.xml containing the following sample data: "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2> <child3 /><child4 /></parent2></document>" A valid XML string, such as: "<document><parent1><child1 /><child2 attribute2=\"b\" /></parent1> <parent2 /></document>" /* * * * * Create variables to store XML objects and strings. Use XMLObject to store a valid XML object such as an XML file. Use sourceXMLString to store a valid XML string. The script sets the content of XMLString to sourceXMLString. The script assigns values to the empty variables later on */

var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test.xml", true ); var sourceXMLString = "<document><parent1><child1 /><child2 attribute2=\"b\" /></parent1><parent2 /></document>"; var XMLString = new XML(); XMLString = XMLString.setContent( sourceXMLString ); var XMLSource; var TargetNode; var searchResults; var siblingResults; /* * * * * * Create a function that searches an XML object (node) for a particular element (targetElem) and returns an XML object containing the element. This function assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data, it returns only the first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement();

77

} node = childNode; } else { node = childNode; } } return node; } /* Create a function to print the target element and search results */ function printFindResults( target, searchResult ) { if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); return searchResult; } else { print( "Cannot find " + target ); return null; } } /* Create a function to find the next sibling element of the target * element */ function findNextSibling( sourceObject, targetNode ) { var startingNode = findTargetElement( sourceObject, targetNode ); var nextSibling = startingNode.getNextSiblingElement(); if ( nextSibling != null ) { return nextSibling; } else { return null; } } /* Create a function to print the first attribute of the target * element */ function printSiblingResults( target, searchResult ) { if ( searchResult != null ) { var childName = searchResult.getNodeName(); print( "The next sibling element of " + target + " is: " + childName ); } else { print( "There are no sibling elements of " + target ); } } /* Set variables to search the XMLFile for the TargetNode. * Run functions findTargetElement, printFindResults, findAttribute, * and printAttributeResults on the XMLFile and TargetNode */ print( "Processing XML from XMLFile... \n" ); TargetNode = "child3"; XMLSource = XMLFile; print( "The target element we are looking for is: " + TargetNode ); searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( TargetNode, searchResults ); siblingResults = findNextSibling( XMLSource, TargetNode );

78

printSiblingResults( TargetNode, siblingResults ); /* Set variables to search the XMLString for the TargetNode. * Run functions findTargetElement, printFindResults, findAttribute, * and printAttributeResults on the XMLString and TargetNode */ print( "Processing XML from XMLString... \n" ); TargetNode = "child1"; XMLSource = XMLString; print( "The target element we are looking for is: " + TargetNode ); searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( TargetNode, searchResults ); siblingResults = findNextSibling( XMLSource, TargetNode ); printSiblingResults( TargetNode, siblingResults );

XML.getNodeName()
This method returns a string representing the name of the current element or attribute; or returns null if the current node has no name. Use the other XML getxxx methods to navigate through an XML document. The syntax is: getNodeName() No arguments are passed. Example This example displays the names of the elements and attributes in an XML document. It requires the following sample data: A local XML file, such as a file called C:\test.xml containing the following sample data: "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2> <child3 /><child4 /></parent2></document>" A valid XML string, such as: "<document><parent1><child1>0123</child1></parent1></document>" /* * * * * Create variables to store XML objects and strings. Use XMLObject to store a valid XML object such as an XML file. Use sourceXMLString to store a valid XML string. The script sets the content of XMLString to sourceXMLString. The script assigns values to the empty variables later on */

var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test.xml", true ); var sourceXMLString = "<document><parent1><child1>0123</child1></parent1></document>"; var XMLString = new XML(); XMLString = XMLString.setContent( sourceXMLString ); var XMLSource; function walkXML( elem ) { print( "Element " + elem.getNodeName() ); var node = elem.getFirstAttribute(); while( node != null ) { var attrName = node.getNodeName(); var attrValue = node.getNodeValue(); print( "Attribute " + attrName + " = " + attrValue ); node = elem.getNextAttribute(); } var nodeValue = elem.getNodeValue(); if ( typeof nodeValue == "string" && nodeValue.length > 0 ) {

79

print( "Element value of " + elem.getNodeName() + " is: " + nodeValue ); } var child = elem.getFirstChildElement(); while( child != null ) { var nodeName = child.getNodeName(); var nodeValue = child.getNodeValue(); walkXML( child ); child = child.getNextSiblingElement(); } } print( "Now printing the structure of an XML file...\n" ); XMLSource = XMLFile; walkXML( XMLSource ); print( "Now printing the structure of an XML string...\n" ); XMLSource = XMLString; walkXML( XMLSource );

XML.getNodeType()
This method evaluates an XML object and returns an integer representing the XML Document Object Model (DOM) type of the current element or attribute; or returns null if the method cannot determine the XML DOM type. (See the W3C Web site for a complete listing of XML DOM node types by integer.) This method returns a type error if applied to anything other than an XML object. This limits this method to elements and attributes because the ServiceCenter XML object cannot represent element values as an XML object. Use the other XML.getxxx methods to navigate through an XML document. The syntax is getNodeType() No arguments are passed. Example This example displays the XML DOM types of the elements and attributes in an XML document. It requires a local XML file, such as a file called C:\test.xml containing the following sample data: "<document><parent1>value1<child1 attribute1="a" /><child2 /></parent1><parent2> <child3 /><child4 /></parent2></document>" function visitElement( elem ) { print( "Element " + elem.getQualifiedName() + " is of type " + elem.getNodeType() ); /* Print attributes for this element */ var node = elem.getFirstAttribute(); while( node != null ) { var attrName = node.getQualifiedName(); var attrValue = node.getNodeValue(); print( "Attribute " + attrName + "=" + attrValue + " and is of type " + node.getNodeType() ); node = elem.getNextAttribute(); } /* Print possible element value */ var nodeValue = elem.getNodeValue(); if ( typeof nodeValue == "string" && nodeValue.length > 0 ) { print( "Element value is " + nodeValue + " and is of type " + elem.getNodeType() ); } /* Now print child elements */

80

var child = elem.getFirstChildElement(); while( child != null ) { var nodeName = child.getNodeName(); var nodeValue = child.getNodeValue(); visitElement( child ); child = child.getNextSiblingElement(); } } var xmlObj = new XML(); xmlObj.setContent( "c:\\test.xml", true ); visitElement( xmlObj.getDocumentElement() );

XML.getNodeValue()
The method returns a string representing the value of the current XML element; or returns null if the current node has no value. This method requires you use the other XML get methods to navigate through an XML document. The syntax is: getNodeValue() No arguments are passed. Example This example displays the value of the elements in an XML document. It requires a local XML file, such as a file called C:\test02.xml containing the following sample data: "<document><parent1>value1</parent1><parent2></parent2></document>" /* * * * * Create variables to store XML objects and strings. Use XMLObject to store a valid XML object such as an XML file. Use sourceXMLString to store a valid XML string. The script sets the content of XMLString to sourceXMLString. The script assigns values to the empty variables later on */

var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test02.xml", true ); var XMLSource; var TargetNode; /* * * * * * Create a function that searches an XML object (node) for a particular element (targetElem) and returns an XML object containing the element. This fuction assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data, it returns only the first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement(); } node = childNode; }

81

else { node = childNode; } } return node; } /* Create a function to print the target element and search results */ function printFindResults( searchResult, targetNode ) { print( "The target element we are looking for is: " + targetNode ); if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); findValue( searchResult, targetNode ); return searchResult; } else { print( "Cannot find " + target ); return null; } } /* Create a function to find the parent node element of the target * element */ function findValue( sourceObject, targetNode ) { var valueFound = sourceObject.getNodeValue(); if ( valueFound.length >= 1 ) { print( "The value of " + targetNode + " is: " + valueFound ); return valueFound; } else { print( "There is no value for " + targetNode ); valueFound = null; return valueFound; } } /* Set variable values for XMLFile and TargetNode. Run functions. print( "Processing XML from XMLFile... \n" ); TargetNode = "parent1"; XMLSource = XMLFile; searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( searchResults, TargetNode ); /* Set variable values for XMLFile and TargetNode. Run functions. print( "Processing XML from XMLFile... \n" ); TargetNode = "parent2"; XMLSource = XMLFile; searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( searchResults, TargetNode ); */ */

XML.getParentNode(Element)
This method returns an XML object representing the parent node of the current node; or returns null if the XML object has no parent node. The syntax is:

82

getParentNode() Or getParentNode(Element) The following argument is valid for this method:


Argument Node Data type String Description Contains the name of the element you want the method to use as the starting position when searching for the parent node element.

Example This example displays the parent node element of any element you select. The example allows you to select an element from two different input sources. It requires the following sample data: A local XML file, such as a file called C:\test.xml containing the following sample data: "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2> <child3 /><child4 /></parent2></document>" A valid XML string, such as: "<document><parent1><child1 /><child2 attribute2=\"b\" /></parent1> <parent2 /></document>" /* * * * * Create variables to store XML objects and strings. Use XMLObject to store a valid XML object such as an XML file. Use sourceXMLString to store a valid XML string. The script sets the content of XMLString to sourceXMLString. The script assigns values to the empty variables later on */

var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test.xml", true ); var sourceXMLString = "<document><parent1><child1 /><child2 attribute2=\"b\" /></parent1><parent2 /></document>"; var XMLString = new XML(); XMLString = XMLString.setContent( sourceXMLString ); var XMLSource; var TargetNode; var searchResults; var parentResults; /* * * * * * Create a function that searches an XML object (node) for a particular element (targetElem) and returns an XML object containing the element. This function assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data, it returns only the first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement();

83

} node = childNode; } else { node = childNode; } } return node; } /* Create a function to print the target element and search results */ function printFindResults( target, searchResult ) { if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); return searchResult; } else { print( "Cannot find " + target ); return null; } } /* Create a function to find the parent node of the target element */ function findParent( sourceObject, targetNode ) { var startingNode = findTargetElement( sourceObject, targetNode ); var parentNode = startingNode.getParentNode(); if ( parentNode != null ) { return parentNode; } else { return null; } } /* Create a function to print the first attribute of the target * element */ function printParentResults( target, searchResult ) { if ( searchResult != null ) { var parentName = searchResult.getNodeName(); print( "The parent node element of " + target + " is: " + parentName ); } else { print( "There is no parent node elements of " + target ); } } /* Set variables to search the XMLFile for the TargetNode. * Run functions findTargetElement, printFindResults, findAttribute, * and printAttributeResults on the XMLFile and TargetNode */ print( "Processing XML from XMLFile... \n" ); TargetNode = "child3"; XMLSource = XMLFile; print( "The target element we are looking for is: " + TargetNode ); searchResults = findTargetElement( XMLSource, TargetNode );

84

printFindResults( TargetNode, searchResults ); parentResults = findParent( XMLSource, TargetNode ); printParentResults( TargetNode, parentResults ); /* Set variables to search the XMLString for the TargetNode. * Run functions findTargetElement, printFindResults, findAttribute, * and printAttributeResults on the XMLString and TargetNode */ print( "Processing XML from XMLString... \n" ); TargetNode = "child1"; XMLSource = XMLString; print( "The target element we are looking for is: " + TargetNode ); searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( TargetNode, searchResults ); parentResults = findParent( XMLSource, TargetNode ); printParentResults( TargetNode, parentResults );

XML.getPrefix()
This method returns a string representing the namespace value of the current node (element or attribute); or returns null if the current node has no namespace value.. Use the other XML.getxxx methods to navigate through an XML document. The syntax is: getPrefix() No arguments are passed. Example This example displays the namespace value of the elements and attributes in an XML document. It requires a local XML file, such as a file called C:\namespace.xml containing the following sample data: <?xml version="1.0" encoding="UTF-8" standalone="yes" ?><document xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:ns="http://servicecenter.peregrine.com/PWS"><http:element1 /><ns:element2 /></document> /* * * * * Create variables to store XML objects and strings. Use XMLObject to store a valid XML object such as an XML file. Use sourceXMLString to store a valid XML string. The script sets the content of XMLString to sourceXMLString. The script assigns values to the empty variables later on */

var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\namespace.xml", true ); var XMLSource; var TargetNode; var searchResults; var prefixResults; var firstAttribute; var attributeResults; /* * * * * * Create a function that searches an XML object (node) for a particular element (targetElem) and returns an XML object containing the element. This fuction assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data it only returns the first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null)

85

{ childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement(); } node = childNode; } else { node = childNode; } } return node; } /* Create a function to print the target element and search results */ function printFindResults( searchResult, targetNode ) { print( "The target element we are looking for is: " + targetNode ); if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); findPrefix( searchResult, targetNode ); return searchResult; } else { print( "Cannot find " + target ); return null; } } /* Create a function to find the parent node element of the target element */ function findPrefix( sourceObject, targetNode ) { var prefixFound = sourceObject.getPrefix(); if ( prefixFound.length >= 1 ) { print( "The namespace prefix of " + targetNode + " is: " + prefixFound ); return prefixFound; } else { print( "There is no namespace prefix of " + targetNode ); prefixFound = null; return prefixFound; } } /* Create a function to find the first attribute of the target element */ function findFirstAttribute( sourceObject, targetNode ) { var startingNode = findTargetElement( sourceObject, targetNode ); var firstAttribute = startingNode.getFirstAttribute(); if ( firstAttribute != null ) { var attributeName = firstAttribute.getNodeName(); print( "The first attribute of " + targetNode + " is: " + attributeName ); findPrefix( firstAttribute, targetNode );

86

return firstAttribute; } else { print( "There are no attributes of " + targetNode ); return null; } } /* Create a function to find the next attribute of the target element */ function findNextAttribute( sourceObject, targetNode ) { var startingNode = findTargetElement( sourceObject, targetNode ); var firstAttribute = startingNode.getFirstAttribute(); if ( firstAttribute != null ) { var nextAttribute = startingNode.getNextAttribute(); while ( nextAttribute != null ) { var attributeName = nextAttribute.getNodeName(); print( "The next attribute of " + targetNode + " is: " + attributeName ); findPrefix( nextAttribute, targetNode ); nextAttribute = nextAttribute.getNextAttribute(); } print( "There are no more attributes of " + targetNode ); return targetNode; } else { return null; } } /* Set variable values for XMLFile and TargetNode. Run functions. */ print( "Processing XML from XMLFile... \n" ); TargetNode = "element1"; XMLSource = XMLFile; searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( searchResults, TargetNode ); /* Set variable values for XMLFile and TargetNode. Run functions. print( "Processing XML from XMLFile... \n" ); TargetNode = "document"; XMLSource = XMLFile; searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( searchResults, TargetNode ); findFirstAttribute( XMLSource, TargetNode ); findNextAttribute( XMLSource, TargetNode ); */

XML.getQualifiedName()
This method, which is a synonym for getNodeName(), returns a string representing the name of the current element or attribute; or returns null if the current node has no name. Use the other XML.getxxx methods to navigate through an XML document. The syntax for this method is: getQualifiedName() No arguments are passed. Example This example displays the names of the elements and attributes in an XML document. It requires a local XML file, such as a file called C:\namespace.xml containing the following sample data: <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <document xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"

87

xmlns:ns="http://servicecenter.peregrine.com/PWS"><http:element1 /> <ns:element2 /></document> /* Create variables to store XML objects and strings. * Use XMLObject to store a valid XML object such as an XML file. * The script assigns values to the empty variables later on */ var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\namespace.xml", true ); var XMLSource; function nsXMLWalk( elem ) { print( "Element " + elem.getQualifiedName() ); var node = elem.getFirstAttribute(); while( node != null ) { var attrName = node.getQualifiedName(); var attrValue = node.getNodeValue(); print( "Attribute " + attrName + " = " + attrValue ); node = elem.getNextAttribute(); } var nodeValue = elem.getNodeValue(); if ( typeof nodeValue == "string" && nodeValue.length > 0 ) { print( "Element value of " + elem.getQualifiedName() + " is: " + nodeValue ); } var child = elem.getFirstChildElement(); while( child != null ) { var nodeName = child.getQualifiedName(); var nodeValue = child.getNodeValue(); nsXMLWalk( child ); child = child.getNextSiblingElement(); } } function walkXML( elem ) { print( "Element " + elem.getName() ); var node = elem.getFirstAttribute(); while( node != null ) { var attrName = node.getName(); var attrValue = node.getNodeValue(); print( "Attribute " + attrName + " = " + attrValue ); node = elem.getNextAttribute(); } var nodeValue = elem.getNodeValue(); if ( typeof nodeValue == "string" && nodeValue.length > 0 ) { print( "Element value of " + elem.getName() + " is: " + nodeValue ); } var child = elem.getFirstChildElement(); while( child != null ) { var nodeName = child.getName(); var nodeValue = child.getNodeValue(); walkXML( child ); child = child.getNextSiblingElement(); } } print( "Now printing the structure of an XML file with qualified names...\n" ); XMLSource = XMLFile; nsXMLWalk( XMLSource );

88

print( "Now printing the structure of an XML file without qualified names...\n" ); XMLSource = XMLFile; walkXML( XMLSource );

XML.getText()
This method, which is a synonym for getNodeValue(), returns a string representing the value of the current XML element; or returns null if the current node has no value. Use the other XML.getxxx methods to navigate through an XML document. The syntax is: getText() No arguments are passed. Example This example displays the value of the elements in an XML document. It requires a local XML file, such as a file called "C:\test02.xml" containing the following sample data: "<document><parent1>value1</parent1><parent2></parent2></document>" /* * * * * Create variables to store XML objects and strings. Use XMLObject to store a valid XML object such as an XML file. Use sourceXMLString to store a valid XML string. The script sets the content of XMLString to sourceXMLString. The script assigns values to the empty variables later on */

var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test02.xml", true ); var XMLSource; var TargetNode; /* * * * * * Create a function that searches an XML object (node) for a particular element (targetElem) and returns an XML object containing the element. This fuction assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data, it returns only the first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement(); } node = childNode; } else { node = childNode; } } return node; }

89

/* Create a function to print the target element and search results */ function printFindResults( searchResult, targetNode ) { print( "The target element we are looking for is: " + targetNode ); if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); findValue( searchResult, targetNode ); return searchResult; } else { print( "Cannot find " + target ); return null; } } /* Create a function to find the parent node element of the target * element */ function findValue( sourceObject, targetNode ) { var valueFound = sourceObject.getText(); if ( valueFound.length >= 1 ) { print( "The value of " + targetNode + " is: " + valueFound ); return valueFound; } else { print( "There is no value for " + targetNode ); valueFound = null; return valueFound; } } /* Set variable values for XMLFile and TargetNode. Run functions. print( "Processing XML from XMLFile... \n" ); TargetNode = "parent1"; XMLSource = XMLFile; searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( searchResults, TargetNode ); /* Set variable values for XMLFile and TargetNode. Run functions. print( "Processing XML from XMLFile... \n" ); TargetNode = "parent2"; XMLSource = XMLFile; searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( searchResults, TargetNode ); */

*/

XML.getValue()
This method, which is a synonym for getNodeValue(), returns a string representing the value of the current XML element; or returns null if the current node has no value. Use the other XML.getxxx methods to navigate through an XML document. The syntax is: getValue() No arguments are passed. Example This example displays the value of the elements in an XML document. It requires a local XML file, such as a file called "C:\test02.xml" containing the following as sample data:

90

"<document><parent1>value1</parent1><parent2></parent2></document>" /* * * * * Create variables to store XML objects and strings. Use XMLObject to store a valid XML object such as an XML file. Use sourceXMLString to store a valid XML string. The script sets the content of XMLString to sourceXMLString. The script assigns values to the empty variables later on */

var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test02.xml", true ); var XMLSource; var TargetNode; /* * * * * * Create a function that searches an XML object (node) for a particular element (targetElem) and returns an XML object containing the element. This fuction assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data, it returns only the first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement(); } node = childNode; } else { node = childNode; } } return node; } /* Create a function to print the target element and search results */ function printFindResults( searchResult, targetNode ) { print( "The target element we are looking for is: " + targetNode ); if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); findValue( searchResult, targetNode ); return searchResult; } else { print( "Cannot find " + target ); return null; } } /* Create a function to find the parent node element of the target * element */

91

function findValue( sourceObject, targetNode ) { var valueFound = sourceObject.getValue(); if ( valueFound.length >= 1 ) { print( "The value of " + targetNode + " is: " + valueFound ); return valueFound; } else { print( "There is no value for " + targetNode ); valueFound = null; return valueFound; } } /* Set variable values for XMLFile and TargetNode. Run functions. print( "Processing XML from XMLFile... \n" ); TargetNode = "parent1"; XMLSource = XMLFile; searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( searchResults, TargetNode ); /* Set variable values for XMLFile and TargetNode. Run functions. print( "Processing XML from XMLFile... \n" ); TargetNode = "parent2"; XMLSource = XMLFile; searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( searchResults, TargetNode ); */

*/

XML.importNode(name)
This method returns an XML object containing a copy of the source XML node; or returns null if the method cannot import a copy of the node. It requires two existing XML objects with document elements: one is the source XML object and the other is the target XML document. This method does not update either the source or the target XML object. Instead, you use the appendNode method to add the imported node into the target XML document. The syntax is: importNode( name ) The following argument is valid for this method:
Argument name Data type String Description Specifies the XML node name you want to copy from the source XML object. Must contain characters valid for XML (for example, the string cannot include the characters < or > except as XML entities such as &lt; and &gt;).

Example This example imports an XML node from one XML object to another. It requires the following sample data: A local XML file, such as a file called "C:\test.xml" containing: "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2> <child3 /><child4 /></parent2></document>" An XML object, such as an object containing: "<document> </document>" var XMLFile = new XML(); var XMLObject = new XML(); var TargetNode; function findTargetElement( node, targetElem )

92

{ while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement(); } node = childNode; } else { node = childNode; } } return node; } /* Create a function to print the target element and search results */ function printFindResults( target, searchResult ) { if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); return searchResult; } else { print( "Cannot find " + target ); return null; } } function importNewNode( xmlSource, xmlTarget, node ) { print( "The XML source object is:\n" + xmlSource ); print( "The target element we are looking for is: " + node ); var FoundNode = findTargetElement( xmlSource, node ); printFindResults( node, FoundNode ); print( "The XML target object is:\n" + xmlTarget ); print( "Importing " + FoundNode + " into XML target object..." ); var NewNode = xmlTarget.importNode( FoundNode ); print( "The XML target object reamins unchanged: " + xmlTarget ); print( "Appending " + FoundNode + " into XML target object..."); var appendedNode = xmlTarget.appendNode( NewNode ); print( "The new XML target object is: " + xmlTarget ); } XMLFile = XMLFile.setContent( "C:\\test.xml", true ); XMLObject = XMLObject.setContent( "<document> </document>" ); TargetNode = "parent1"; importNewNode( XMLFile, XMLObject, TargetNode );

XML.isDocumentElement()
This method returns true if the current element is the Document Object Model (DOM) document element (the "root" node of the XML document); and returns false if it is not. Use the XML.getxxx methods to navigate through an XML document.

93

The syntax is: isDocumentElement() No arguments are passed. Example This example checks whether the selected element is the DOM document element. It requires a local XML file, such as a file called C:\test02.xml containing: "<document><parent1>value1</parent1><parent2></parent2></document>" /* * * * * Create variables to store XML objects and strings. Use XMLObject to store a valid XML object such as an XML file. Use sourceXMLString to store a valid XML string. The script sets the content of XMLString to sourceXMLString. The script assigns values to the empty variables later on */

var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test02.xml", true ); var XMLSource; var TargetNode; /* * * * * * Create a function that searches an XML object (node) for a particular element (targetElem) and returns an XML object containing the element. This fuction assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data it returns only the first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement(); } node = childNode; } else { node = childNode; } } return node; } /* Create a function to print the target element and search results */ function printFindResults( searchResult, targetNode ) { print("The target element we are looking for is: " + targetNode ); if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); testDocElem( searchResult); return searchResult;

94

} else { print( "Cannot find " + target ); return null; } } /* Create a function to find the parent node element of the target * element */ function testDocElem( sourceObject ) { var docElement = sourceObject.isDocumentElement(); if ( docElement == true ) { var nodeName = sourceObject.getName(); print( "Success. The element " + nodeName + " is the DOM document element." ); return valueFound; } else { var nodeName = sourceObject.getName(); print( "Fail. The element " + nodeName + " is not the DOM document element." ); valueFound = null; return valueFound; } } /* Set variable values for XMLFile and TargetNode. Run functions. print( "Processing XML from XMLFile... \n" ); TargetNode = "parent1"; XMLSource = XMLFile; searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( searchResults, TargetNode ); /* Set variable values for XMLFile and TargetNode. Run functions. print( "Processing XML from XMLFile... \n" ); TargetNode = "document"; XMLSource = XMLFile; searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( searchResults, TargetNode ); */

*/

XML.setAttributeValue(AttributeName, AttributeValue)
This method adds or updates the attribute value of the target attribute. Use the XML.getxxx methods to navigate through an XML document. This method does not return any values. The syntax is: setAttributeValue( AttributeName, AttributeValue ) The following arguments are valid for this method:
Argument AttributeName AttributeValue Data type String String Description The XML attribute whose value you want the script to add or update. Specifies the text string you want the script to use as the XML attribute value. Must contain characters valid for an XML element (for example, the string cannot include the characters < or >).

Example This example adds or updates the attribute value of any given element in an XML document. It requires a local XML file, such as a file called C:\test.xml containing the following sample data: "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2> <child3 /><child4 /></parent2></document>"

95

/* Create variables to store XML objects and strings. * Use XMLFile to store a valid XML file. * The script assigns values to the empty variables later on */ var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test.xml", true ); var XMLSource; var TargetNode; var TargetAttribute; var TargetValue; var searchResults; /* * * * * * Create a function that searches an XML object (node) for a particular element (targetElem) and returns an XML object containing the element. This fuction assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data, it returns only the first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement(); } node = childNode; } else { node = childNode; } } return node; } /* Create a function to print the target element and search results */ function printFindResults( target, searchResult, attributeName, attributeValue ) { print( "The target element we are looking for is: " + target ); if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); var attributeSet = setAttributeValue( searchResult, attributeName, attributeValue ); print( "The XML object is " + searchResult ); return attributeSet; } else { print( "Cannot find " + target ); return null; } } /* Create a function to set the attribute value of the target * attribute */ function setAttributeValue( sourceObject, attributeName, attributeValue )

96

{ print( "Setting attribute value of " + attributeName ); var setAttributeValue = sourceObject.setAttributeValue( attributeName, attributeValue ); var newAttributeValue = sourceObject.getAttributeValue( attributeName ); print( "The value of " + attributeName + " is now " + newAttributeValue ); return newAttributeValue; } /* Set variable values for XMLFile and TargetNode. Run functions */ print( "Processing XML from XMLFile... \n" ); TargetNode = "child1"; XMLSource = XMLFile; TargetAttribute = "attribute1"; TargetValue = "z"; searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( TargetNode, searchResults, TargetAttribute, TargetValue ); print( "Processing XML from XMLFile... \n" ); TargetNode = "child2"; XMLSource = XMLFile; TargetAttribute = "attribute1"; TargetValue = "z"; searchResults = findTargetElement( XMLSource, TargetNode ); printFindResults( TargetNode, searchResults, TargetAttribute, TargetValue );

XML.setContent(String) or XML.setContent("FilePath", IsFile)


This method creates an XML object, either from a string or the contents of an external file object, if it was able to successfully parse the XML input. It always creates a valid XML document with a document element, and removes any values outside the document element. This method returns null if applied to an existing XML object because the header information ([C++ object XML] @nnnnnnnnnn - ) is not valid XML. Use the toXMLString method to convert an XML object to an XML string. The syntax is: setContent( String ) Or setContent( "FilePath", IsFile ) The following arguments are valid for this method:
Argument String FilePath Data type String String Description Specifies the text string you want the script to parse as on XML object. Must contain a valid XML document with a document element. Specifies the path to the XML document you want the script to parse an XML object. To indicate that the String argument is a file path and not a string value, enclose the FilePath argument in quotation marks, and set the IsFile argument to true. Specifies whether the String argument is a string or a file path. A true value indicates the String argument is a file path. Any other value, including omitting the second argument, indicates that the String argument is a text string.

IsFile

Boolean

Example This example attempts to create an XML object from five different sources. It requires the following sample data: A valid XML string, such as: "<document><parent1><child1 attribute1=\"1\" /></parent1><parent2 /></document>"

97

An XML string with more than one document element, such as: "<document1><parent1 /></document1><document2><parent2 /></document2>" A local XML file, such as a file called C:\test.xml containing the following sample data: "<document><parent1><child1 attribute1="a" /><child2 /></parent1><parent2> <child3 /><child4 /></parent2></document>" An existing XML object, such as the list of currently logged-on users stored in system.users An XML object converted to a string, such as the list of currently logged on users stored in system.users /* Create a function to execute the setContent method. * The function creates a new XML object xmlObj. * It sets the content of the XML object to the source argument. * The isFile argument determines if the source is an XML string or * file path. * If setContent returns true, it prints an XML string and returns the * XML object. * If setContent returns false, it prints the source and returns null. */ function setXML( source, isFile ) { var xmlObj = new XML(); if ( xmlObj.setContent( source, isFile ) ) { var xmlDoc = xmlObj.toXMLString(); print( "setContent succeeded! \n The XML document is: \n" + xmlDoc ); return xmlObj; } else { print( "setContent failed. \n Could not parse the following input as XML: \n" + source ); return null; } } /* * * * * * * * Create variables to store your XML source objects. Use xmlObject to test setting content to an XML object. xmlObjectConverted converts xmlObject to an XML string. Note: The toXMLstring method removes the object header information. Use xmlString to test setting content to an XML string. Note: You must use the backslash character to escape out quotation marks in your XML string. Use xmlFile to test setting content to an XML file. */

var xmlString = "<document><parent1><child1 attribute1=\"1\" /></parent1><parent2 /></document>"; var xmlBad = "<document1><parent1 /></document1><document2><parent2 /></document2>"; var xmlFile = "C:\\test.xml"; var xmlObject = system.users; var xmlObjectConverted = xmlObject.toXMLString(); /* Note: You can omit the isFile argument when the content source is * an XML string. * See the xmlString example below. */ print( "Testing setting content to a valid XML string...\n" ); setXML( xmlString ); print( "Testing setting content to an XML string with more than one document element...\n" ); print( "The non-compliant XML string before conversion is: \n" + xmlBad ); setXML( xmlBad ); print( "Testing setting content to an XML file...\n" );

98

setXML( xmlFile, true ); print( "Testing setting content to an existing XML object...\n" ); setXML( xmlObject, false ); print( "Testing setting content to an existing XML object converted to an XML string...\n" ); setXML( xmlObjectConverted, false );

XML.setNodeValue(String)
This method is used to add or update the value of the current element. It returns an XML object containing the new value of the current element; or returns null if the method cannot set a value for the element. Use the XML.getxxx methods to navigate through an XML document. The syntax is: setNodeValue( String ) The following argument is valid for this method:
Argument String Data type String Description Specifies the text string you want the script to add as the XML element value. Must contain characters valid for XML (for example, the string cannot include the characters < or > except as XML entities such as &lt; and &gt;).

Example This example sets the value of the elements in an XML document. It requires a local XML file, such as C:\test03.xml containing: "<document><parent1></parent1><parent2></parent2></document>" /* * * * * Create variables to store XML objects and strings. Use XMLObject to store a valid XML object such as an XML file. Use sourceXMLString to store a valid XML string. The script sets the content of XMLString to sourceXMLString. The script assigns values to the empty variables later on */

var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test03.xml", true ); var TargetNode; var TargetValue; var findElement; /* * * * * * Create a function that searches an XML object (node) for a particular element (targetElem) and returns an XML object containing the element. This fuction assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data it only returns the first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement(); } node = childNode;

99

} else { node = childNode; } } return node; } /* Create a function to print the target element and search results */ function setElementValue( searchResult, targetNode, newValue ) { print( "The target element we are looking for is: " + targetNode ); if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); searchResult.setNodeValue( newValue ); print("The new value of " + targetNode + " is: " + searchResult); return searchResult; } else { print( "Cannot find " + targetNode ); return null; } } TargetNode = "parent1"; TargetValue = "1234"; findElement = findTargetElement( XMLFile, TargetNode ); setElementValue( findElement, TargetNode, TargetValue );

XML.setText(String)
This method, which is a synonym for setNodeValue(), is used to add or update the value of the current element. It returns an XML object containing the new value of the current element; or returns null if the method cannot set a value for the element. Use the XML.getxxx methods to navigate through an XML document. The syntax is: setText( String ) The following argument is valid for this method:
Argument String Data type String Description Specifies the text string you want the script to add as the XML element value. Must contain characters valid for XML (for example, the string cannot include the characters < or > except as XML entities such as &lt; and &gt;).

Example This example sets the value of the elements in an XML document. It requires a local XML file, such as C:\test03.xml containing "<document><parent1></parent1><parent2></parent2></document>" /* * * * * Create variables to store XML objects and strings. Use XMLObject to store a valid XML object such as an XML file. Use sourceXMLString to store a valid XML string. The script sets the content of XMLString to sourceXMLString. The script assigns values to the empty variables later on */

var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test03.xml", true ); var TargetNode;

100

var TargetValue; var findElement; /* * * * * * Create a function that searches an XML object (node) for a particular element (targetElem) and returns an XML object containing the element. This fuction assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data it only returns the first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement(); } node = childNode; } else { node = childNode; } } return node; } /* Create a function to print the target element and search results */ function setElementValue( searchResult, targetNode, newValue ) { print( "The target element we are looking for is: " + targetNode ); if ( searchResult != null ) { var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); searchResult.setText( newValue ); print("The new value of " + targetNode + " is: " + searchResult); return searchResult; } else { print( "Cannot find " + targetNode ); return null; } } TargetNode = "parent1"; TargetValue = "1234"; findElement = findTargetElement( XMLFile, TargetNode ); setElementValue( findElement, TargetNode, TargetValue );

XML.setValue(String)
This method, which is a synonym for setNodeValue(), is used to add or update the value of the current element. It returns an XML object containing the new value of the current element; or returns null if the method cannot set a value for the element. Use the XML.getxxx methods to navigate through an XML document.

101

The syntax is: setValue( String ) The following argument is valid for this method:
Argument String Data type String Description Specifies the text string you want the script to add as the XML element value. Must contain characters valid for XML (for example, the string cannot include the characters < or > except as XML entities such as &lt; and &gt;).

Example This example sets the value of the elements in an XML document. It requires as sample data a local XML file, such as a file called C:\test03.xml containing: "<document><parent1></parent1><parent2></parent2></document>" /* * * * * Create variables to store XML objects and strings. Use XMLObject to store a valid XML object such as an XML file. Use sourceXMLString to store a valid XML string. The script sets the content of XMLString to sourceXMLString. The script assigns values to the empty variables later on */

var XMLFile = new XML(); XMLFile = XMLFile.setContent( "C:\\test03.xml", true ); var TargetNode; var TargetValue; var findElement; /* * * * * * Create a function that searches an XML object (node) for a particular element (targetElem) and returns an XML object containing the element. This fuction assumes that there is only one instance of the target element in the source data. If it finds more than one element in the data it only returns the first instance of the element. */

function findTargetElement( node, targetElem ) { while (node != null && node.getNodeName() != targetElem ) { var childNode = node.getFirstChildElement(); if (childNode == null) { childNode = node.getNextSiblingElement(); while (childNode == null) { node = node.getParentNode(); if ( node == null ) { return null; } childNode = node.getNextSiblingElement(); } node = childNode; } else { node = childNode; } } return node; } /* Create a function to print the target element and search results */ function setElementValue( searchResult, targetNode, newValue ) { print( "The target element we are looking for is: " + targetNode ); if ( searchResult != null )

102

{ var elementName = searchResult.getNodeName(); print( "Found element " + elementName + " in: \n" + searchResult + "\n" ); searchResult.setValue( newValue ); print( "The new value of " + targetNode + " is: " + searchResult ); return searchResult; } else { print( "Cannot find " + targetNode ); return null; } } TargetNode = "parent1"; TargetValue = "1234"; findElement = findTargetElement( XMLFile, TargetNode ); setElementValue( findElement, TargetNode, TargetValue );

XML.toXMLString()
This method converts an XML object into a valid XML string; or returns null if the current node is not an XML object. Use the XML.getxxx methods to navigate through an XML document. The syntax for use is: toXMLString() No arguments are passed. Example This example converts an XML object into a valid XML document. It requires as sample data an existing XML object, such as the list of currently logged on users stored in system.users. var xmlObject = print( "This is var xmlString = print( "This is xmlString ); system.users; the original XML object:\n" + xmlObject ); xmlObject.toXMLString(); the XML object after conversion to a string:\n" +

JavaScript methods for the XMLDate object


XMLDate.addDuration(duration)
This method returns an XMLDate object containing the new date/time after adding the duration from the duration argument; or returns null if the conversion fails. The syntax is: addDuration( duration ) The following argument is valid for this function:
Argument duration Data type ISO 8601 duration string Required Yes Description Contains the ISO 8601 duration string or variable value you want the script to add to an XMLDate object.

Example This example creates a new XMLDate object containing today's date; adds 1 year, 2 months, 3 days, and 4 hours to the XMLDate object; and then displays the result print( "Creating XMLDate object..." ); var d = new XMLDate( new Date() );

103

print( "The value of the print( "Adding 1 year, 2 var dur = d.addDuration( print( "The value of the

new XMLDate object is: " + d ); months, 3 days, and 4 hours to date..." ); "P1Y2M3DT4H" ); new XMLDate object is: " + dur );

XMLDate.getDate()
This method returns a JavaScript date/time object as a string; or null if the conversion fails. The syntax is: getDate() Example This example creates a new XMLDate object containing today's date; converts the XMLDate object to JavaScript date/time object; and then displays the result. print( "Creating XMLDate object..." ); var d = new XMLDate( new Date() ); print( "The value of the new XMLDate object is: " + d ); print( "Converting the XMLDate to a JavaScript object..." ); var js = d.getDate(); print( "The JavaScript date/time object is: " + js );

XMLDate.getDatum()
The method returns a ServiceCenter-formatted date/time Datum object in a string; or returns null if the conversion fails. The syntax is: getDatum() No arguments are passed. Example This example creates a new XMLDate object containing today's date; converts the XMLDate object to ServiceCenter-formatted date/time Datum object; and then displays the result. print( "Creating XMLDate object..." ); var d = new XMLDate( new Date() ); print( "The value of the new XMLDate object is: " + d ); print( "Converting the XMLDate to a ServiceCenter Datum..." ); var sc = d.getDatum(); print( "The ServiceCenter Datum object is: " + sc );

XMLDate.getGMTSCDateTimeString()
The method returns a ServiceCenter-formatted date/time string; or returns null if the conversion fails. The syntax is: getSCDateTimeString() No arguments are passed. Example This example creates a new XMLDate object containing today's date; converts the XMLDate object to ServiceCenter-formatted date/time string; and then displays the result. print( "Creating XMLDate object..." ); var d = new XMLDate( new Date() ); print( "The value of the new XMLDate object is: " + d ); print("Converting the XMLDate to a ServiceCenter date/time string..."); var sc = d.getGMTSCDateTimeString(); print( "The ServiceCenter GMT date/time string is: " + sc );

104

XMLDate.getISODate()
The getISODate() method returns a string containing the date portion of a date/time object in ISO format; or returns null if the conversion fails. The syntax is: getISODate() No arguments are passed. Example This example creates a new XMLDate object containing today's date; converts the XMLDate object to an ISO date; and then displays the result. print( "Creating XMLDate object..." ); var d = new XMLDate( new Date() ); print( "The value of the new XMLDate object is: " + d ); print( "Converting the XMLDate to ISO format..." ); var ISO = d.getISODate(); print( "The ISO date is: " + ISO );

XMLDate.getISODateTimeString()
This method returns a string containing the date and time portion of date/time object in ISO format; or returns null if the conversion fails. The syntax is: getISODateTimeString() No arguments are passed. Example This example creates a new XMLDate object containing today's date; converts the XMLDate object to an ISO date and time; and then displays the result. print( "Creating XMLDate object..." ); var d = new XMLDate( new Date() ); print( "The value of the new XMLDate object is: " + d ); print( "Converting the XMLDate to ISO format..." ); var ISO = d.getISODateTimeString(); print( "The ISO date and time is: " + ISO );

XMLDate.getISODay()
This method returns a string containing the day portion of date/time object in ISO format; or returns null if the conversion fails. The syntax is: getISODay() No arguments are passed. Example This example creates a new XMLDate object containing today's date; converts the XMLDate object to an ISO day; and then displays the result. print( "Creating XMLDate object..." ); var d = new XMLDate( new Date() ); print( "The value of the new XMLDate object is: " + d ); print( "Converting the XMLDate to ISO format..." ); var ISO = d.getISODay(); print( "The ISO day is: " + ISO );

XMLDate.getISOMonth()
This method returns a string containing the month portion of date/time object in ISO format; or returns null if the conversion fails. The syntax is:

105

getISOMonth() No arguments are passed. Example This example creates a new XMLDate object containing today's date; converts the XMLDate object to an ISO month; and then displays the result. print( "Creating XMLDate object..." ); var d = new XMLDate( new Date() ); print( "The value of the new XMLDate object is: " + d ); print( "Converting the XMLDate to ISO format..." ); var ISO = d.getISOMonth(); print( "The ISO month is: " + ISO );

XMLDate.getISOTime()
This method returns a string containing the time portion of date/time object in ISO format; or returns null if the conversion fails. The syntax is: getISOTime() No arguments are passed. Example This example creates a new XMLDate object containing today's date; converts the XMLDate object to an ISO time; and then displays the result. print( "Creating XMLDate object..." ); var d = new XMLDate( new Date() ); print( "The value of the new XMLDate object is: " + d ); print( "Converting the XMLDate to ISO format..." ); var ISO = d.getISOTime(); print( "The ISO time is: " + ISO );

XMLDate.getISOYear()
This method returns a string containing the year portion of date/time object in ISO format; or returns null if the conversion fails. The syntax is: getISOYear() No arguments are passed. Example This example creates a new XMLDate object containing today's date; converts the XMLDate object to an ISO year; and then displays the result. print( "Creating XMLDate object..." ); var d = new XMLDate( new Date() ); print( "The value of the new XMLDate object is: " + d ); print( "Converting the XMLDate to ISO format..." ); var ISO = d.getISOYear(); print( "The ISO year is: " + ISO );

XMLDate.getSCDateTimeString()
This method returns a ServiceCenter-formatted date/time string; or returns null if the conversion fails. The syntax is: getSCDateTimeString() No arguments are passed.

106

Example This example creates a new XMLDate object containing today's date; converts the XMLDate object to ServiceCenter-formatted date/time string; and then displays the result. print( "Creating XMLDate object..." ); var d = new XMLDate( new Date() ); print( "The value of the new XMLDate object is: " + d ); print("Converting the XMLDate to a ServiceCenter date/time string..."); var sc = d.getSCDateTimeString(); print( "The ServiceCenter date/time string is: " + sc );

XMLDate.JSDate()
This method, which is an alias of the getDate() method, returns a JavaScript date/time object; or returns null if the conversion fails. The syntax is: JSDate() No arguments are passed. Example This example creates a new XMLDate object containing today's date; converts the XMLDate object to a JavaScript date/time object; and then displays the result. print( "Creating XMLDate object..." ); var d = new XMLDate( new Date() ); print( "The value of the new XMLDate object is: " + d ); print( "Converting the XMLDate to a JavaScript object..." ); var js = d.JSDate(); print( "The JavaScript date/time object is: " + js );

XMLDate.toSCDuration(duration)
This method returns a string containing the new ServiceCenter duration converted from an ISO 8601 duration; or returns null if the conversion fails. The syntax is: toSCDuration( duration ) The following argument is valid for this function:
Argument duration Data type ISO 8601 duration string Required Yes Description Contains the ISO 8601 duration string or variable value you want the script to convert to a ServiceCenter duration.

Example This example creates a new XMLDate object containing a hard-coded ISO date; converts the ISO date/time to a ServiceCenter duration; and displays the result. print( "Creating XMLDate object..." ); var d = new XMLDate( "P01DT12H01M01S" ); print( "The value of the new XMLDate object is: " + d ); print( "Converting " + d.toString() + " to a SC duration..." ); var scDur = d.toSCDuration(); print( "The ServiceCenter duration is: " + scDur );

107

Cross-reference: Index of methods and functions by task


Array handling
ServiceCenter arrays are held in Datum, SCDatum or SCFile objects. They have to be converted to a JavaScript array by using the toArray method. As an example, the following code shows how to check and fill an array: CI=new SCFile("device") var array_incidents = new Array(); var ind = 0; while(CI.array_incidents[ind] != null) { array_incidents[ind]=CI.array_incidents[ind]; ind++; } /* ********************************************************************** The following statement achieves the same results as the above whileloop: array_incidents=CI.array_incidents.toArray ********************************************************************** */ var j=0; /* ********************************************************************** Since indexOf is not available on Arrays, the array has to be converted to a string before using this function to find if a single element is part of the array. ********************************************************************** */ var temp_string = array_incidents.toString(); var i = temp_string.indexOf(incNumber); /* ********************************************************************** the next set of statements can be replaced by the push() method. The lines of code would be as follows: if (i<0) { var newArrayLength = array_incidents.push( incNumber ); ********************************************************************** */ if (i < 0) { if (array_incidents == null) { j=0; } else { j=array_incidents.length; } array_incidents[j] = incNumber; }

Topic

Page 29 30 31

Description Creates an ServiceCenter-formatted Datum object containing the provided record, structure, or array. Creates an SCDatum object containing the provided record, structure, or array. (alias of SCFile). Creates an SCFile object containing the provided record, structure, or array.

Datum SCDatum SCFile

108

Topic

Page 45 50 51 53 53 56 57 58

Description Returns the number of array elements in an array. Returns the elements of either a ServiceCenter Datum array object or a JavaScript array as a string. Returns the number of array elements in an array. Removes the last element from a JavaScript array and returns the element removed as a string. Adds an entry to the end of a JavaScript array and returns the total number of entries in the array. Removes the first element from a JavaScript array and returns the element removed as a string. Converts a ServiceCenter Datum object into a JavaScript array. Adds an entry to the beginning of a JavaScript array and returns the total number of entries in the array.

SCFile.getSize() SCFile.join() SCFile.length() SCFile.pop() SCFile.push() SCFile.shift() SCFile.toArray() SCFile.unshift()

Date/Time handling
Topic Page 34 50 Description Creates or converts to an XML Date object. Converted ServiceCenter date/time data into JavaScript date/time objects (SCFile now automatically converts ServiceCenter date/time data into JavaScript date/time objects). Returns an XMLDate object containing the new date/time after adding the duration from the duration argument. Returns a JavaScript date/time object as a string. Returns a ServiceCenter-formatted date/time Datum object in a string. Returns a ServiceCenter-formatted date/time string. Returns a string containing the date portion of a date/time object in ISO format. Returns a string containing the date and time portion of date/time object in ISO format. Returns a string containing the day portion of date/time object in ISO format. Returns a string containing the month portion of date/time object in ISO format. Returns a string containing the time portion of date/time object in ISO format. Returns a string containing the year portion of date/time object in ISO format. Returns a ServiceCenter-formatted date/time string. Returns a JavaScript date/time object. Returns a string containing the new ServiceCenter duration converted from an ISO 8601 duration.

XMLDate SCFile.JSDate()

XMLDate.addDuration() XMLDate.getDate() XMLDate.getDatum() XMLDate.getGMTSCDateTimeString() XMLDate.getISODate() XMLDate.getISODateTimeString() XMLDate.getISODay() XMLDate.getISOMonth() XMLDate.getISOTime() XMLDate.getISOYear() XMLDate.getSCDateTimeString() XMLDate.JSDate() XMLDate.toSCDuration()

103 104 104 104 105 105 105 105 106 106 106 107 107

109

Database or file manipulation


Topic Page 29 30 31 38 37 39 39 40 41 42 43 44 44 49 55 18 18 21 20 Description Creates an ServiceCenter-formatted Datum object containing the provided record, structure, or array. Creates an SCDatum object containing the provided record, structure, or array. (alias of SCFile). Creates an SCFile object containing the provided record, structure, or array. Creates a ServiceCenter record. Removes a ServiceCenter record (alias of SCFile.doRemove). Removes a ServiceCenter record. Adds to or updates the ServiceCenter database. Runs the specified query and returns a list of records matching the query.. Updates a ServiceCenter record. Returns the first record in a record list. Returns the last record in a record list. Returns the next record in a record list. Returns the previous record in a record list. Verifies that the query or query condition returns a ServiceCenter record. Adds or updates a ServiceCenter record with the new field value defined in the newValue argument. Calls the last ServiceCenter record into memory. Calls the current ServiceCenter record into memory. Writes the contents of the object parameter to the file specified in the path parameter. Reads the contents of a local file and returns a string object with the contents of that file.

Datum SCDatum SCFile SCFile.doInsert() SCFile.doDelete() SCFile.doRemove() SCFile.doSave() SCFile.doSelect() SCFile.doUpdate() SCFile.getFirst() SCFile.getLast() SCFile.getNext() SCFile.getPrev() SCFile.isRecord() SCFile.setValue() system.oldrecord system.record writeFile readFile

Basic functionality
Topic Page 16 16 17 17 18 18 18 18 18 19 19 Description Calls a particular ServiceCenter table into memory. Calls a particular ServiceCenter form into memory. Calls a particular ServiceCenter RAD function from JavaScript. Calls a particular ServiceCenter script library function. Calls the last ServiceCenter record into memory. Calls the current ServiceCenter record into memory. Calls an XML list of properties about the ServiceCenter server. Calls an XML list of the current ServiceCenter threads into memory. Calls an XML list of properties of the currently logged on ServiceCenter user. Calls an XML list of the currently logged on ServiceCenter users into memory. Calls a particular ServiceCenter variable into memory.

system.files system.forms system.functions system.library system.oldrecord system.record system.sysinfo system.threads system.user system.users system.vars

110

Topic

Page 11 11

Description Operators used in query expressions. Integer values to test the values returned by the methods of objects.

Query Operators JavaScript return code properties print Quit doHTTPRequest doSOAPRequest help RCtoString execute compile Attachment Header

20 21 23 24 26 26 27 27 28 28

Displays the contents of the method argument in the client Messages view and also prints it in the ServiceCenter log file. Stops the processing of JavaScript from the point it is called and returns a failure return code. Sends an HTTP request to a remote server specified by a URL. Issues a SOAP request to a remote server specified by an URL and returns the SOAP response in a string or an error message. Displays a brief description of a ServiceCenter-defined JavaScript object. Converts a ServiceCenter global return code value into a localized text string. Validates the syntax of a JavaScript. Validates the syntax of a JavaScript (alias of execute). Contains attachment data for use with doSOAPRequest methods. Creates a (HTTP) Header object.

Conversions
Topic Page 22 22 23 50 Description Converts binary data to a base-64 string format. Converts base-64 string data to its original format. Converts a JavaScript string to an XML-formatted string. Converted ServiceCenter date/time data into JavaScript date/time objects (SCFile now automatically converts ServiceCenter date/time data into JavaScript date/time objects). Set the data type of ServiceCenter datum objects (SCFile now automatically converts ServiceCenter data types into JavaScript data types). Converts a ServiceCenter Datum object into a JavaScript array. Converts an XML object into a valid XML string.

base64Encode base64Decode xmlstring SCFile.JSDate()

SCFile.setType() SCFile.toArray() XML.toXMLString()

54 57 103

XML
Topic Page 18 18 18 19 23 33 34 Description Calls an XML list of properties about the ServiceCenter server. Calls an XML list of the current ServiceCenter threads into memory. Calls an XML list of properties of the currently logged on ServiceCenter user. Calls an XML list of the currently logged on ServiceCenter users into memory. Converts a JavaScript string to an XML-formatted string. Creates an empty XML object where you can store and manipulate XML documents. Creates or converts to an XML Date object.

system.sysinfo system.threads system.user system.users xmlstring XML XMLDate

111

Topic

Page 48 59 60 62 63 64 66 67 68 71 73 74 76

Description Returns an XML object representation of the current SCFile object. Inserts an attribute and attribute value into the current element. Inserts an XML element as a child of the current element. Inserts an XML node into an XML object. Creates an XML node from an XML object . Returns an XML object containing the target attribute the current element. Returns the string value of the target attribute. Searches an XML object for the DOM document element (or "root" node). Returns an object representing the first attribute of the current node. Returns an object representing the first child node of the current node. Returns a string representing the name of the current element. Returns an object representing the first attribute of the current node. Returns an object representing the next node at the same level in the DOM tree as the current node. Returns a string representing the name of the current element or attribute. Evaluates an XML object and returns an integer representing the XML DOM type of the current element or attribute. Returns a string representing the value of the current XML element. Returns an XML object representing the parent node of the current node. Returns a string representing the namespace value of the current node (element or attribute). Returns a string representing the name of the current element or attribute. Returns a string representing the value of the current XML element (alias for getNodeValue). Returns a string representing the value of the current XML element (alias for getNodeValue). Returns an XML object containing a copy of the source XML node. Returns the Boolean value of true if the current element is the DOM document element (the "root" node of the XML document) or false if it is not. Adds or updates the attribute value of the target attribute. Creates an XML object from a string or the contents of an external file object if it was able to successfully parse the XML input. Adds or updates the value of the current element. Adds or updates the value of the current element (alias for setNodeValue). Adds or updates the value of the current element (alias for setNodeValue). Converts an XML object into a valid XML string. Returns an XMLDate object containing the new date/time after adding the duration from the duration argument. Returns a JavaScript date/time object as a string. Returns a ServiceCenter-formatted date/time Datum object in a string

SCFile.getXML() XML.addAttribute() XML.addElement() XML.appendNode() XML.createNode() XML.getAttributeNode() XML.getAttributeValue() XML.getDocumentElement() XML.getFirstAttribute() XML.getFirstChildElement() XML.getName() XML.getNextAttribute() XML.getNextSiblingElement( ) XML.getNodeName() XML.getNodeType() XML.getNodeValue() XML.getParentNode() XML.getPrefix() XML.getQualifiedName() XML.getText() XML.getValue() XML.importNode() XML.isDocumentElement()

79 80 81 82 85 87 89 90 92 93

XML.setAttributeValue() XML.setContent() XML.setNodeValue() XML.setText() XML.setValue() XML.toXMLString() XMLDate.addDuration() XMLDate.getDate() XMLDate.getDatum()

95 97 99 100 101 103 103 104 104

112

Topic

Page 104

Description Returns a ServiceCenter-formatted date/time string

XMLDate.getGMTSCDateTi meString() XMLDate.getISODate() XMLDate.getISODateTimeS tring() XMLDate.getISODay() XMLDate.getISOMonth() XMLDate.getISOTime() XMLDate.getISOYear() XMLDate.getSCDateTimeSt ring() XMLDate.JSDate() XMLDate.toSCDuration()

105 105

Returns a string containing the date portion of a date/time object in ISO format Returns a string containing the date and time portion of date/time object in ISO format Returns a string containing the day portion of date/time object in ISO format Returns a string containing the month portion of date/time object in ISO format Returns a string containing the time portion of date/time object in ISO format Returns a string containing the year portion of date/time object in ISO format Returns a ServiceCenter-formatted date/time string

105 105 106 106 106

107 107

Returns a JavaScript date/time object Returns a string containing the new ServiceCenter duration converted from an ISO 8601 duration

113

For more information


Please visit the HP OpenView support web site at:
http://www.hp.com/managementsoftware/support

This web site provides contact information and details about the products, services, and support that HP OpenView offers. HP OpenView online software support provides customer self-solve capabilities. It provides a fast and efficient way to access interactive technical support tools needed to manage your business. As a valuable support customer, you can benefit by being able to: Search for knowledge documents of interest Submit and track progress on support cases Submit enhancement requests online Download software patches Manage a support contract Look up HP support contacts Review information about available services Enter discussions with other software customers Research and register for software training Note: Most of the support areas require that you register as an HP Passport user and sign in. Many also require an active support contract. To find more information about support access levels, go to the following URL:
http://www.hp.com/managementsoftware/access_level

To register for an HP Passport ID, go to the following URL:


http://www.managementsoftware.hp.com/passport-registration.html

2006 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice. The only warranties for HP products and services are set forth in the express warranty statements accompanying such products and services. Nothing herein should be construed as constituting an additional warranty. HP shall not be liable for technical or editorial errors or omissions contained herein. HP, OpenView, and ServiceCenter are registered trademarks of Hewlett-Packard Development Company, L.P. Java and JavaScript are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. Mozilla is a registered trademark of the Mozilla Foundation. Visual Basic is a registered trademark of Microsoft Corporation in the United States and other countries. All other trademarks are the property of their respective owners. 12/2006

Вам также может понравиться