Descripción: Service Manual for a T2300 Design Jet Plotter
HP deskjetFull description
IPG-FIBER-LASER
Descripción: HP
Full description
Descripción completa
Comandos para HP 2620Descripción completa
About This Book This book provides an in‐depth examination of NFV, including the individual components of the NFV Reference Architecture and Hewlett Packard Enterprise’s vision for the future of...
Deskripsi lengkap
Full description
Descrição: HP 12c
AccutronFull description
Service Manager® 7.0 JavaSc JavaScript ript Programming Guide ™
Using JavaScript in Service Manager 7.0 7. 0 Tailoring Tailoring Tools HP® Management Software Service Management
Introduction......................................................................................................................................... 4 Requirements................................................................................................................................... 4 How to use this document ................. ........................... ................... .................. .................. .................. .................. .................. .................. .................. ................... .............. .... 4 Introduction to JavaScript in Service Manager......................... Manager.................................. .................. ................... ................... .................. .................. .................. ......... 4 Language overview overvie w ................................... .................. ................................... ................................... ................................... .................................... .................................. ................ 4 Basic rules of JavaScript.................................................................................................................... 5 Structure of a JavaScript application .................. ........................... .................. .................. .................. .................. .................. .................. ................... .............. .... 5 Expressions and operators............................................................................................................. 5 JavaScript objects and properties ................... ............................ .................. .................. .................. .................. .................. .................. .................. ................. ........ 6 Built-in objects and functions .................. ........................... .................. .................. .................. ................... ................... .................. .................. .................. ............... ...... 6 Conditional statements .................. ............................ ................... .................. .................. .................. .................. .................. .................. .................. ................... .............. .... 6 While and loop statements ................... ............................ .................. .................. .................. .................. .................. .................. .................. ................... ................. ....... 6 Break and continue statements .................. ........................... .................. .................. ................... ................... .................. .................. .................. .................. ............ ... 7 Exception Handling statements..................... statements.............................. .................. .................. ................... ................... .................. .................. .................. .................. ......... 8 Use of JavaScript in Service Manager .................. ........................... .................. .................. ................... ................... .................. .................. .................. .................. ......... 8 Order of execution of JavaScript versus RAD language.................. language........................... ................... ................... .................. .................. .................. ......... 8 The ScriptLibrary ScriptL ibrary ................................. ................ ................................... ................................... ................................... .................................... ................................... .................... ... 10 Using the ScriptLibrary .................. ............................ ................... .................. .................. .................. .................. .................. .................. .................. ................... ............ .. 10 Corresponding JavaScript J avaScript syntax for f or RAD language tasks ................. .......................... ................... ................... .................. .................. ............. .... 11 JavaScript global properties ............................................................................................................ 12 Query operators......................................................................................................................... 12 JavaScript return code properties.............. properties....................... .................. .................. .................. .................. .................. .................. .................. ................... ............ .. 12 Examples of calling JavaScript from different Service Manager tools ................. ........................... ................... .................. ................ ....... 13 FormatControl FormatCon trol ................................. ................ ................................... .................................... ................................... ................................... ................................... .................... ... 13 Triggers..................................................................................................................................... 14 Links ......................................................................................................................................... 16 Programmer’s reference...................................................................................................................... 17 JavaScript global system objects .................. ........................... .................. .................. .................. .................. .................. .................. .................. ................... ............ .. 17 system.files system.f iles .................................. ................. ................................... .................................... ................................... ................................... ................................... ....................... ...... 18 system.forms system.f orms ................................... .................. ................................... .................................... ................................... ................................... ................................... .................... ... 18 system.functions ......................................................................................................................... 19 system.library............................................................................................................................. 19 system.oldrecord system.ol drecord ................................... .................. ................................... ................................... ................................... .................................... ................................ .............. 20 system.record............................................................................................................................. 20 system.sysinfo system.sy sinfo ................................. ................ ................................... .................................... ................................... ................................... ................................... .................... ... 20 system.threads ........................................................................................................................... 21
Introduction System administrators can now use the standard JavaScript scripting language to customize their Service Manager applications. JavaScript is a widely supported, supported, industry-standard industry-standard programming language that eliminates the need for a separate programming skill set, and reduces user reliance on proprietary tools. tools. The introduction of JavaScript into Service Manager does not invalidate invalidate the current Service Manager RAD tool set; instead, the JavaScript interface is an alternative to the RAD language for tailoring.
Requirements This document is targeted for Service Manager system administrators and assumes that the reader is familiar with object-oriented programming programming and JavaScript development. development. It provides an overview of JavaScript functionality in Service Manager, 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 Service Manager introduces basic rules of JavaScript and describes its use in Service Manager. The section Use of JavaScript in Service Manager describes the use of the JavaScript language as it relates to Service Manager customization customization and tailoring. It provides detailed examples examples to aid beginners who are developing their first JavaScript application in Service Manager. The Programmer’s reference is a complete complete reference reference for JavaScript JavaScript in Service Service Manager. It includes includes information and key examples for all available objects, properties, and methods.
Introduction to JavaScript in Service Manager Like RAD, JavaScript in Service Manager provides the ability to query, insert, update, and delete database records, records, and to make use of existing existing RAD variables and functions. functions. The principal benefit of using JavaScript is that it uses an industry-standard scripting language to execute commands instead of a proprietary language. language. JavaScript within Service Manager is implemented using the Mozilla® SpiderMonkey (JavaScript–C) Engine. For detailed information about the syntax of Mozilla SpiderMonkey JavaScript, refer to: http://developer.mozilla.org/en/do http://develope r.mozilla.org/en/docs/Core_JavaScript_1.5 cs/Core_JavaScript_1.5_Guide _Guide
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 dynamically typed scripting scripting language that offers programming programming tools with easy syntax and built-in functionality. Unlike programming languages, scripting languages do not use compilers to create executable program program code. Because Because JavaScript JavaScript is an interpreted interpreted language, language, each time the script is executed, it is loaded loaded into an interprete interpreterr that runs the code. The Compile Compile button in the Script Library does not create create an executable load module; it runs a syntax check to verify that the script is executable.
4
JavaScript can be either client-side, server-side, or or core language. Core JavaScript is the base JavaScript language with client-side and server-side JavaScript as extensions. extensions. Server-side JavaScript is used for accessing and manipulating data, and is the only one available within Service Manager.
Basic rules of JavaScript The following rules apply to the basic syntax of JavaScript:
JavaScript is case-sensitive. Statements should end in a semicolon (;) or line break. Variables … …Must …Must be defined before being used. used. The variable variable name can contain contain A – Z, a – z, underscore or digits and must start with a letter or an underscore (“_”). …Assume …Assume the type of the data that is put into the variable. variable. The data type type does not have to be explicitly defined. …Are global variables global variables when defined outside of a function, and are available anywhere in the current application application.. Variables Variables created created within a function function are local variables, local variables, and can be used only within that function. Strings Strings have to be enclosed in quotation quotation marks, marks, either a single or double. For example: example: print(”Hello ” + ‘world ‘+ Country.name) produces the following: following: Hello world US. Special characters that are displayed literally must be preceded by a backslash character (\). Quotes Quotes within a string can be entered entered preceded preceded by a backslash backslash as well. well. See
Core Language Features - Literals - "String literals" section for more information. To increment increment a variable, variable, such as a = a + 1, you can use a++. You can decrement decrement a variable 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 ArrayList=new Array(”test”, ” this”, ” list”); Dots in Service Manager Manager field names must be replaced by an underscore underscore (_) in JavaScript JavaScript.. For example contact.name becomes contact_name. Service Manager field names that are reserved words in JavaScript have to be preceded by an underscore, such as “_class” for the “class” field.
Structure Structure of a JavaScript JavaScript application declarations;> function (() rs>) { }
Expressions Expressions and operators For more information on this topic refer to: http://developer.mozilla.org/en/do http://develope r.mozilla.org/en/docs/Core_JavaScript_1.5 cs/Core_JavaScript_1.5_Guide _Guide
Expressions and Operators section.
5
The list of operators includes assignment operators, comparison operators, arithmetic operators, bitwise operators, logical operators, string operators, and special operators.
JavaScript JavaScript objects and properties The key to understand understanding ing JavaScript JavaScript is learning learning the structure structure of its objects. objects. JavaScript JavaScript is an objectobjectoriented language with many similarities to the C programming programming language. Most JavaScript functionality functionality is contained contained in objects. The objects objects contain methods, methods, parameter parameters, s, and events. Each object may contain contain a set of properties properties that more closely closely define the object. JavaScript JavaScript objects objects do not have normal class-to-subclass class-to-subclass relationships: Subclasses are contained contained within classes but do not inherit their properties. The syntax syntax you use to call methods methods and properties is: Object.method or Object.property. For more information on JavaScript objects and properties refer to: http://developer.mozilla.org/en/do http://develope r.mozilla.org/en/docs/Core_JavaScript_1.5 cs/Core_JavaScript_1.5_Guide _Guide
Details of the Object Model section.
Built-in Built-in objects and functions 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://developer.mozilla.org/en/do http://develope r.mozilla.org/en/docs/Core_JavaScript_1.5 cs/Core_JavaScript_1.5_Guide _Guide
See Working With Objects – Predefined Core Objects 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 conditional statement statement to shorten shorten the "if" expressio expressions. ns. The statement: statement: var retur return n = (parm (parm.D .Date ate.g .getD etDat ate e <= 30) ? true true : false false; ;
Works in the same way as its much longer equivalent: var return=false; return=false; if (parm.D (parm.Date. ate.getD getDate ate <= 30) { retur return n = true true; ; } else { return=false; }
While and loop statements Whenever programming programming a loop statement, statement, ensure ensure that the exit condition condition will be met; Note: Note: Whenever otherwise an infinite loop will occur. For detailed information about the for and while loop statements, refer to http://developer.mozilla.org/en/do http://develope r.mozilla.org/en/docs/Core_JavaScript_1.5 cs/Core_JavaScript_1.5_Guide _Guide
See Statements – Loop Statements section.
6
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 DivisableByTwoF DivisableByTwoFOR(ParmN OR(ParmNumber) umber) { for for (var (var i=0; i=0; Parm ParmNu Numb mber er > 1; i++) i++) { ParmN ParmNumb umber er = ParmN ParmNumb umber er / 2; } return return i; } fuction DivisableByTwoW DivisableByTwoWHILE(pa HILE(parmNumber rmNumber) ) { v ar i = 0 ; whil while( e( Parm ParmNu Numb mber er > 1 ) { ParmN ParmNumb umber er = ParmN ParmNumb umber er / 2; i++; } return return i; }
Note: Note: A Do..While Do..While loop is available available for those those instances when you want to execute a statement statement (or block of statements) statements) at least once. In a Do..While loop the exit condition condition is checked after the after the statements are executed.
Break and continue statements The break statement terminates terminates a "while" or "for" loop completely. The continue statement terminates 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 { v ar i v ar n whil while e { if {
break4error(par break4error(parmArray, mArray, x) = 0; = 0; (i < 10) 10) (isNaN(parmArra (isNaN(parmArray[x])) y[x])) print(p print(parmA armArray rray[i]. [i].toSt toStrin ring g + “ is not numeric. numeric. Please Please repair repair and and run run again again”; ”; break;
} n = n + parm parmAr Arra ray[ y[i] i]; ; i++; } return return n; }
Modifying the above example, the continue statement would work as follows: function { v ar i v ar n whil while e { if
{ print(p print(parmA armArray rray[i]. [i].toSt toStrin ring g + “ is not numeric. numeric. Continu Continuing ing with next number”; number”; i++; continue; } n = n + parm parmAr Arra ray[ y[i] i]; ; i++; } return return n; }
Exception Handling statements As a best practice, exception handling should always be included in any JavaScript program. function SetFullName SetFullName (FirstName,LastN (FirstName,LastName) ame) { if (Firs (FirstNa tName me != null null || LastN LastNam ame e != null) null) { FullN FullName ame=F =Firs irstN tName ame + “ “ + LastN LastNam ame e return FullName FullName } else { throw "InvalidName" "InvalidName" } } try { // state stateme ments nts to try try Var MyName= MyName=SetF SetFullN ullName( ame(Fir First, st, Last) Last) // function function could could throw throw exceptio exception n } catch catch (e) { MyName="unknown" logMyEr logMyErrors rors(e) (e) // pass pass excepti exception on object object to error error handler handler }
For detailed information about exception handling, refer to http://developer.mozilla.org/en/do http://develope r.mozilla.org/en/docs/Core_JavaScript_1.5 cs/Core_JavaScript_1.5_Guide _Guide
See Statements – Exception Handling Statements section.
Use of JavaScript in Service Manager You can use JavaScript in the tailoring tools listed below in Service Manager 7.0x. In addition to these areas where JavaScript can be entered directly, the functions entered in the ScriptLibrary can be accessed from anywhere in Service Manager 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.
8
FormatControl The JavaScript is executed after calculations after calculations and before valid before validation ations. s. JavaScript JavaScript code code in FormatControl is executed via the format.cjavascript RAD. Links JavaScript in links is executed after the after the (initial) expressions, but before the before the fill or find find is executed 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, us.find, respectively, on the eval.post.expressions eval.post.expressions panel. panel. Triggers The JavaScript JavaScript in the triggers triggers file is executed after the RAD application. application. This is controlled 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. process.update.config.recor d. The evaluate expressions 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: areas: During File Selection, Actions, and Cancel Expressions.
File Selection: Selection: The Select $L.file by tab information information is processe processed d first, followed by the Initial Initial Expressions tab and the JavaScript tab. Actions: Actions: In the Actions Actions tab, the Expressions Expressions are run first, first, then the JavaScript, JavaScript, followed followed by the information on the Format Control / Process Name tab. Cancel Expressions: Here first the Expressions Executed Executed on Cancel tab are processed, processed, followed by Javascript Executed on Cancel tab.
Interoperability (ioaction file) The ioaction file executes only JavaScript JavaScript,, and not RAD, expressions. expressions. The JavaScript 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
9
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 Service Manager used to create, edit, compile, test, and store scripts and functions that can be called and executed from anywhere within Service Manager. Some of these stored JavaScript programs can be used to interface with 3 rd party Web Services providers, such as real-time real-time currency conversions. All of these JavaScripts JavaScripts are identified as SOAP packages within the ScriptLibrary. ScriptLibrary. Integrations are typically typically performed through JavaScript JavaScript stored in the Script Library as well. Adminstrative Mode Mode when entering entering the ScriptLibrary ScriptLibrary,, since functions such as Note: Note: Do not use Adminstrative compile and execute are not available in that mode.
Using the ScriptLibrary ScriptLibrary The Script Library Library has several sections. sections. The name of the record is used to call the JavaScript JavaScript via either system.library.<scriptname system.library.<scriptname >.., >, or via jscall(). jscall(). The package package field is used to group records for easier maintenance. A syntax-highlighted script editor editor is used to enter JavaScript JavaScript code. The color codes that the script editor uses are:
Red: Keywo Keywords rds Green: Objects, methods, and properties as well as function names Teal: Comme Comments nts Blue: String Stringss Magenta: curly braces, operators, punctuation characters Black: Black: Default Default color color
The screen displayed below shows how all these colors appear in the script editor:
10
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 run 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 Service Manager that supports JavaScript, by using the following syntax: system.library.< scriptname>.( parameters )
Within a ScriptLibrary record, you can call any function that is defined previously within the same record by simply typing: ( parameters )
To call JavaScript from any RAD process panel, you can use the jscall RAD function. The syntax for this function is: jscall( jscall( "script "script.fun .functio ction" n" , 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(tzfuncti jscall(tzfunctions.getT ons.getTZforOpe ZforOperator, rator, “falcon”); “falcon”);
Corresponding JavaScript syntax for RAD language tasks Most Service Manager tasks can be translated from RAD language to JavaScript by using the following table. eM
rt
Dp
l/
te
Create a file variable
rinit
new SCFile(“ SCFile(“filename”)
Select a record
select
”) RC =ObjectName.doSelect(“ Query ”)
11
eM
rt
Dp
l/
te
Update a record
rupdate
RC =ObjectName.doUpdate()
Add a record
radd
RC =ObjectName.doInsert()
Delete a record
rdelete
RC =ObjectName.doRemove()
Refer to a field in a file
result =fieldname in fieldname in filevariable
result=ObjectName.fieldname
Access an element of an array
result =rownumer in rownumer in arrayname in filevariable
JavaScript global properties Global Global properties properties are predefined properties properties that are not part of any object. They are names representing values that are are globally defined. The core JavaScript language language has several global global properties, such as NaN (Not a Number), and Service Manager has a number of additional global properties. There are two categories of Service Manager-defined global properties:
Query operators JavaScript return code properties
Query operators These operators are used solely for constructing query expressions using the Query object. deprecated, but older JavaScript JavaScript code within the ScriptLibr ScriptLibrary ary still Note: Note: The Query object has been deprecated, uses the object. yo EQ
JavaScript JavaScript return code properties properties Use these properties (which are represented internally as integer values) to test the values returned by object methods methods such as SCFile. To print the error message message rather than the return code, code, use the RCtoString function.
12
RC_SUCCESS
The operation succeeded.
RC_ERROR
An unspecified error occurred. Examine the contents of the Messages view or the sm.log file for more information.
RC_C RC_CA ANT_HAV _HAVEE
The The oper perati ation fail faileed bec becaus ause the the resou esourrce is unavai availlabl able beca becauuse some other user or process has the resource locked.
RC_NO_MORE
No more records are available in the result set.
RC_D RC_DUP UPLI LICA CATE TE_K _KEY EY
The The inse insert rt opera perati tion on fail failed ed beca becaus usee the the file file alre alread adyy cont contai ains ns a reco record rd with this unique key value.
RC_MODIFIED
The update operati ation failed becau cause the the record was modified by another user or process since you read it.
RC_DELETED
The operati ation failed becaus ause the record was deleted by another user or process.
RC_BAD_QUERY
The query failed due to incorrect query syntax.
RC_N RC_NOT OT_A _AUT UTHO HORI RIZE ZED D
The The requ reques estt oper operat atio ionn was was not not perf perfor orme med d due due to an auth author oriz izat atio ionn failure. Check the permissions permissions associated with the user who submitted the request.
RC_V RC_VAL ALID IDAT ATIO ION_ N_FA FAIL ILED ED
The The oper operati ation on fail failed ed beca becaus usee the the data data supp supplilied ed in a fiel field d or the the reco record rd did not pass validity checks performed by the application.
The operat operatio ionn faile failed. d. Check Check to make make sure sure the table table name name is correc correct, t, that the table exists, and that it is not read-only.
The The oper operati ation on fail failed ed.. Check Check to make make sure sure the the tabl tablee name name is corr correc ect, t, that the table exists, and that it is not read-only.
The The oper operati ation on fail failed ed.. Check Check to make make sure sure the the tabl tablee name name is corr correc ect, t, that the table exists, and that it is not read-only.
RC_I RC_IN NVALI VALID_ D_FI FILE LENA NAME ME
The The oper operat atio ionn fail failed ed beca becaus usee the the tabl tablee name name is not not vali valid. d.
Example var rc = mySCFil mySCFile.do e.doInse Insert() rt(); ; i f ( r c = = R C _SUCCESS SUCCESS ) { print( print( "Insert "Insert succeed succeeded" ed" ); } Else thro throw( w( "Err "Error or " + RCto RCtoSt Stri ring ng(r (rc) c) + " occu occurr rred ed tryi trying ng to inse insert rt a record" record" );
Examples of calling JavaScript from different Service Manager tools The following examples offer suggestions about using JavaScript in some of the tailoring tools that support this functionality. functionality. Additional JavaScript examples examples can be found in the Programmer’s reference section 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.
13
In the Calculations section of FormatControl, in the initial column enter a condition of the following in the calculation column:
true.
Then add
$assigne $assignee.o e.old ld = nullsub( nullsub(assi assignee gnee.na .name me in $file, $file, “no assigne assignee”) e”)
Click the JavaScript tab, enter true for Add and Update, and enter the following statements: var usersXM usersXML L = system.u system.users sers; ; var usersString usersString = usersXML.toXMLS usersXML.toXMLString() tring(); ; var file = system.v system.vars. ars.$fil $file; e; var newAssi newAssignee gnee = file.as file.assign signee ee _name; system.vars.$IsUser=usersString.indexOf(newAssignee);
In the Validation section enter the following, in the Add and Update column: assignee.name assignee.name in $file~=$assigne $file~=$assignee.old; e.old;
And the following expression in the Validation column: $IsU $IsUse ser r > 0
Enter the following in the Validation message field: The The new new assi assign gnee ee is not not logg logged ed in at this this time time. . Plea Please se try try anot anothe her r 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 variable can be set and used by preceding preceding it with system.var system.vars. s. This lets variable 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, updated, and to whom it is assigned. assigned. Then it adds an activity with the information information that the message has been sent. var NewRecord=syste NewRecord=system.vars. m.vars.$L $L _new; new; /* This This is the the $L.n $L.new ew reco record rd pass passed ed in from from the trigg trigger er */ var incNumber=NewRe incNumber=NewRecord.nu cord.number; mber; var incAssignee=New incAssignee=NewRecord. Record.assignee assignee _name; if (incAssignee==n (incAssignee==null) ull) { incAssi incAssignee gnee="no ="no one at the moment"; moment"; } /* Inser Insert t a mess message age sched schedule ule recor record d into into the the schedu schedule le file file */ function insertSchedule( insertSchedule( incNumber, incNumber, incAssignee, incAssignee, Adressees) Adressees) { var var newS newSche chedu dule le = new SCFil SCFile( e( "sche "schedu dule" le" ); var today=n today=new ew Date(); Date(); newSchedule.app newSchedule.applicatio lication= n= "message.bg"; "message.bg"; newSchedule. _class class = "problem "problem"; "; newSchedule.nam newSchedule.name= e= "message processor record"; newSchedule.exp newSchedule.expiration iration= = today; newSchedule.strings[1]="1"; newSchedule.str newSchedule.strings[2] ings[2]="proble ="problem m update"; newSche newSchedule dule.str .string ings[3] s[3]="Pr ="Proble oblem m " + incNumbe incNumber r + " has been upda update ted. d. It is assi assign gned ed to " + incA incAss ssig igne nee e + "."; ".";
14
newSchedule.strings[5]="pm.main"; newSchedule.str newSchedule.strings[6] ings[6]=" =" Soap-Windows Soap-Windows XP"; newSchedule.strings1=Adressees; var rc = newSche newSchedule dule.doI .doInse nsert() rt(); ; } /* Selec Selects ts the opera operator tors s that that are membe members rs of the assig assignme nment nt grou group p to retur return n to the calli calling ng funct functio ion n */ function selectAddressee selectAddressees(assign s(assignmentGro mentGroup) up) { var var assi assignm gnmen ent t = new SCFil SCFile( e( "assi "assign gnmen ment" t" ); var findAss findAssigne ignee e = assignm assignment. ent.doSe doSelec lect( t( " name=\"" name=\""+ + assignm assignmentG entGrou roup p + "\"" "\"" ); if ( find findAs Assi sign gnee ee == RC _SUCCESS SUCCESS ) { addressList=assignment.operators; return addressList; addressList; } else { print print( ( "Coul "Could d not find find assig assignme nment nt group. group. " + RCtoStri RCtoString( ng( findAss findAssignm ignment ent ) ); return return null; null; } } /* Inser Inserts ts an activ activit ity y with with the the infor informa matio tion n that that the email email notif notifica icati tion on to the the assi assign gnme ment nt grou group p memb member ers s has has been been sent sent */ function addActivity(inc addActivity(incNumber) Number) { var var newA newActi ctivi vity ty = new SCFil SCFile( e( "acti "activi vity" ty" ); var today=n today=new ew Date(); Date(); newActivity.num newActivity.number= ber= incNumber; incNumber; newActivity.dat newActivity.datestamp= estamp= today; newActivity.typ newActivity.type= e= "Update"; "Update"; newActi newActivity vity.des .descri criptio ption[0] n[0]= = "Notifi "Notificati cation on email email on the update update has been sent sent to all membe members rs of the the assig assignme nment nt group group." ."; ; var result = newActivity.doAc newActivity.doAction("a tion("add"); dd"); if (res (resul ult t == RC _CANT _HAVE HAVE || resul result t == 51 ) { system.library.activityUpdates.scheduleActivityUpdate ( newActivity, newActivity, newActivity.ty newActivity.type, pe, newActivity.des newActivity.description cription ); } } /* Sele Select cts s the the oper operat ator ors s to send send the the mess messag age e to */ Addressees Addressees = selectAddressee selectAddressees( s( NewRecord.assi NewRecord.assignment gnment ); if (Addr (Addres essee sees s != null) null) { /* adds adds the the mess messag age e to the the sche schedu dule le file file for for send sendin ing g */ insertSchedule( insertSchedule( incNumber, incNumber, incAssignee, incAssignee, Addressees); Addressees); /* adds adds an acti activi vity ty to info inform rm the the user user of the the emai email l bein being g sent sent*/ */ addActivity(incNumber); }
The example shows (among other things) how to call a Document Engine Action; how to call a function function from the Script Library; Library; and how to insert a new record. In addition, addition, it shows shows how to use several functions within a single JavaScript and how to call them. Because the class class field name name in the schedule file is in conflict with the class keyword used in Note: Note: Because JavaScript, it must be preceded by an underscore (_).
15
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 var CI _Record= Record=new new SCFile( SCFile("dev "device" ice"); ); /* opens opens the device device file file */ var CIName=system.v CIName=system.vars.$Fi ars.$File.logic le.logical al _name name; ; /* pass passes es in the the logi logica cal l name name from from $Fil $File e */ /* Selec Selects ts the confi configur gurat ation ion item item to updat update e */ function function getConf getConfigur iguratio ationIte nItem( m( CIName CIName ) { var findCI findCI _RC = CI _Record. Record.doSe doSelect lect( ( "logical "logical.nam .name=\ e=\""+ ""+ CIName CIName + "\"" ); if (findCI (findCI _RC==RC _SUCCESS) { return return CI _Record; } else { print print( ( "Coul "Could d not find find confi configur gurat ation ion Item. Item. " + RCtoString( RCtoString( findCI _R C ) ) ; return return null; null; } } /* Incre Increas ases es the the use use counte counter r that that count counts s how how often often this this item item was was affec affecte ted d by an incid incident ent ticke ticket t and and ente enters rs the the incid inciden ent t ticke ticket t numbe number r into into the the array array of incid inciden ents ts */ function increaseUseCoun increaseUseCounter(CI) ter(CI) { if (CI.is (CI.is _down down == true true) ) { print print("T ("The he confi configu gurat ratio ion n item item is down down at the the momen moment. t. Pleas Please e check check exis existi ting ng tick ticket ets s if the the caus cause e for for this this issu issue e is rela relate ted d to the the down down system."); } CI.num _issues _on _CI++; CI++; /* incre increase ase count counter er */ var incNumb incNumber er = system.v system.vars ars.$Fi .$File.n le.numbe umber; r; /* get the inciden incident t ticket ticket number number */ var array array _incid inciden ents ts = new Array Array(); (); v ar i nd = 0 ; while(CI.array _incid inciden ents[ ts[in ind] d] != null) null) /* conv convert ert the SC array array into into a JS array array (see (see para paragra graph ph below below) ) */ { array _incidents[ind]=CI.array _incidents[ind]; ind++; } var var j=0; j=0; var var temp temp _strin string g = arra array y _incidents.toString(); var i = tem temp _string.indexOf(incNumber); if (i < 0) /* Chec Check k if inci incide dent nt is alre alread ady y in the the list list */ { /* If not, not, ente enter r the the inci incide dent nt numb number er to the the list list *? if (arra (array y _inciden incidents ts == null) null)
This example shows how to query a record from within Service Manager, and how to update fields in that record. record. Additiona Additionally lly it shows how how to transfer an array array from Service Manager Manager to JavaScript. JavaScript. An array from Service Manager cannot be directly copied into a JavaScript array, because the syntax of Service Manager {“IM1001”, “IM1002”} “IM1002”} does not not work in JavaScript. Properties such as the length length property property assume assume that the value is a function if it is enclosed enclosed in curly braces {}. To successfull successfullyy convert a Service Manager 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-by-element transfer, as shown above. JavaScript it is very important important that you handle handle null values. Functions Functions such as length may not Note: In JavaScript work on null values.
Programmer’s 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 objects JavaScript methods for the XML object JavaScript methods for the XMLDate object
JavaScript global system objects Global Global objects are predefined objects objects that are always instantiated and cannot be created using the “new” “new” operato operator. r. Objects Objects may may have methods and subordinate properties to which you refer using the dot dot (.) operator. The The primary global object is the System object, which acts as a con tainer for an entire entire hierarchy hierarchy of global global objects, all of which are properties propertie s of the System object. Service Manager Manager global global System objects have constructors. Note: ote: None of the Service The following is a complete list of global objects, which are exposed as properties of the System object:
aliases exist for these global system objects, they should not be used. Note: Note: Although some shortcut aliases Scripts that attempt to to use these names as variables variables may not function as expected. expected. Therefore, you must type out the entire global System object name, for example, system.user instead of user. user.
system.files The system.files system.files JavaScript JavaScript object is unique to Service Service Manager. It allows you to call a particular particular Service Service Manager table into memory. memory. Its syntax syntax is: system.files.
. >. There are no arguments and no methods for the system.files object, and the following property is valid for it:
table name
Yes Yes
Spec Specif ifie iess the the tabl tablee name name you you want want to init initia ialilize ze for for proc proces essi sing ng..
Example This example sets a variable equal to system.files.contacts and displays the contents of the contacts table. table. It requires a valid Service Manager table table name (for example, example, contacts) as sample sample data: var f = system. system.file files.co s.contac ntacts; ts; print print( ( "The "The valu value e of system system.f .file iles. s.con conta tacts cts is:\n is:\n" " + f );
system.forms The system.forms system.forms object object allows you to call a particula particularr Service Manager form into memory. memory. It is unique to Service Service Manager. Manager. Its syntax syntax is: system.forms.form_name system.forms.form_name . There are no arguments or methods for this object, and the following property is valid for it:
form_name
Yes Yes
The The name name of the the form form you you want want to brin bring g into into memo memory ry..
Example This example sets a variable equal to system.forms.ScriptLibrary, and displays the contents of the ScriptLibrary form. It requires a valid Service Service Manager form name (for example, example, ScriptLibrary) as sample data: var fm = system. system.form forms.Sc s.Script riptLibr Library ary; ; print print( ( "The "The valu value e of system system.f .form orms. s.Scr Scrip iptLi tLibr brary ary is:\n is:\n" " + fm );
18
system.functions This JavaScript JavaScript object is unique to Service Service Manager. The system.funct system.functions ions object allows allows you to call a particular Service Manager Manager RAD function from JavaScript. Its syntax is: system.functions.RAD system.functions.RAD function name ( RAD function arguments ). The following argument is valid for this object: RAD function arguments
String
Yes
Contai tains any any arguments required to execute the RAD function.
The following property is valid for this object: Property
RAD function name
Required
Yes Yes
Description
Cont Contai ains ns the the RAD RAD func functition on name name you you want want to brin bring g into into memo memory ry..
Example This example sets a variable equal to system.functions.date(), and displays the results of the RAD date() date() function. It requires requires a valid Service Service Manager RAD function function name (for example, example, date()) date()) as sample data: fn = system.function system.functions.date() s.date(); ; print print( ( "The "The valu value e of system system.f .func uncti tions ons.d .date ate() () is:\n" 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 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 Service Manager script script library function. It is unique to Service Service Manager. Manager. The syntax syntax for this object is: system.library.script system.library.script name .function name ( function arguments ). The following argument is valid for this function:
function arguments
Str String ing
Yes Yes
Conta ontain inss the the func functi tio on arg argument ents you want want to use.
No methods are defined for this object. The following following properties properties are valid for this object: object:
script name
Yes Yes
Cont Contai ains ns the the name name of the the scri script pt you you want want to run. run.
function name
No
Cont Contai ains ns the the name name of the the func functi tion on you want want to run. run.
19
Example This example example calls a script from the Script library. library. It requires requires the name of a valid Service Manager Manager script (for example, SelfService) as sample data: print( "Running "Running script system.library. system.library.SelfSer SelfService..." vice..." ) system.library. system.library.SelfServ SelfService.reg ice.registerEss isterEssUser( User( BOB, HELPDESK, HELPDESK, BOB.HELPDESK@ac [email protected], me.com, 858-555-1212 858-555-1212 );
system.oldrecord The system.oldrecord JavaScript object allows you to call a copy of the current Service Manager record before before modificatio modifications ns into memory. memory. It is unique to Service Service Manager. Manager. Its syntax 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. system.oldr oldrecor ecord; d; print print( ( "The "The valu value e of system system.r .reco ecord rd is:\n is:\n" " + o );
system.record The system.record JavaScript object allows you to call the current Service Manager record including the latest latest modifications modifications into memory memory.. It is unique to Service Manager. Manager. The syntax 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. system.reco record; rd; print print( ( "The "The valu value e of system system.r .reco ecord rd is:\n is:\n" " + r );
system.sysinfo The system.sysinfo JavaScript object allows you to get an XML list of properties about the Service Manager Manager server and the client client settings. settings. It is unique to Service Service Manager. Manager. Its syntax 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. system.sysi sysinfo; nfo; print print( ( "The "The valu value e of system system.s .sysi ysinf nfo o is:\ is:\n" n" + s ); The value value of syste system. m.sys sysin info fo is: is: 0
system.threads The system.threads JavaScript object allows you to call an XML list of the current Service Manager threads threads into memory. memory. It is unique to Service Manager. Manager. 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.t system.thre hreads; ads; print print( ( "The "The valu value e of system system.t .thre hread ads s is:\ is:\n" n" + th );
system.user The system.user JavaScript object allows you to call an XML list of properties of the currently logged on Service Service Manager user. user. It is unique to Service Service Manager. Manager. The syntax 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 = syste system. m.use user; r; prin print( t( "The "The valu value e of syst system em.u .use ser r is:\ is:\n" n" + u );
21
system.users The system.users JavaScript object allows you to call an XML list of the currently logged on Service Manager Manager users users into memory. memory. It is unique to Service Service Manager. Manager. The syntax syntax of this object 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. system.user users; s; prin print( t( "The "The valu value e of syst system em.u .use sers rs is:\ is:\n" n" + u );
system.vars The system.vars JavaScript object allows you to call a particular Service Manager variable into memory. memory. It is unique unique to Service Service Manager. Manager. Its syntax syntax is: is: system.vars.variable system.vars.variable name There are no arguments arguments or methods for this object. The following following property property is valid for this object:
variable name
Yes Yes
Cont Contai ains ns the the vari variab able le name name you you want want to brin bring g into into memo memory ry..
Example This example sets a variable equal to system.vars.$L_file, and displays the contents of the $L_file variable variable It requires requires a valid Service Manager Manager variable variable name (for example, example, $L_file) $L_file) as sample sample data: var v = syste system. m.var vars. s.$L $L _file; print( print( "The "The value value of system.v system.vars. ars.$L $L _file file is:\ is:\n" n" + v );
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 global methods directly, just as with any core JavaScript JavaScript global function such as parselnt() or eval().
print Both displays the contents of the argument ("string (" string"" or StringVariable ) in the client Messages view, and prints it in the Service Manager log file. The syntax is: print ("string ("string") ") Or print(StringVariable print(StringVariable ). ). The print method method does not return any value and does not have any throws. throws. The following following argument argument is valid for this function: at
22
"string" or StringVariable
outp output ut
Yes Yes
Cont Contai ains ns the the text text stri string ng or vari variab able le valu valuee you want want the the scri script pt to print to the Message View and the sc.log file. Enclose Enclose literal literal text strings in quotation marks.
Example var examp example le = "abc1 "abc123 23."; ."; print print("T ("The he value value of examp example le is: is: " + exam example ple); );
This example created the following following output: "The value of example is: abc123." abc123."
readFile Reads the contents contents of a local local file and returns 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 argu binary argument. ment. The syntax syntax for this method is: readFile( path, binary ). binary ). The following arguments are valid for this function: at path
Stri String ng
Yes Yes
Cont Contai ains ns the the text text stri string ng or vari variabl ablee valu valuee conta contain inin ing g the the full fullyy qual qualif ifie ied d path of the file to be read. Enclose literal text text strings in quotation marks. marks.
binary
Stri String ng
Yes Yes
Dete Determ rmin ines es whet whethe herr the the fil file form format at is bina binary ry or text text.. Use Use the the stri string ng "b" "b" or "B" to read a binary file. file. Use any other value value to read a text file.
Example This example example reads the contents contents of a text file, and then reads the contents of a binary file. It requires requires both a text file and a binary file on the local file system as sample data. var textF textFil ile e = readF readFile ile( ( "C:\\ "C:\\tes test. t.xml xml", ", "t" "t" ); prin print( t( "The "The valu value e of text textFi File le is: is: " + text textFi File le ); var binFile binFile = readFil readFile( e( "C:\\hea "C:\\header der _left.gi left.gif", f", "b" ); prin print( t( "The "The valu value e of binF binFil ile e is: is: " + binF binFil ile e );
writeFile Writes the contents of the object parameter to a specified path and file, which can be in either binary or text format. format. It returns returns the number of bytes written written to the file. The syntax syntax for calling calling this method is: writeFile( path, path, binary , object ) object ) The following arguments are valid for this function: at path
Stri String ng
Yes
Cont Contai ains ns the the text text stri string ng or vari variabl ablee valu valuee cont contai aini ning ng the the full fullyy qual qualif ifie ied d path of the file to be written. Enclose literal text text strings in quotation marks.
binary
Stri String ng
No
Spec Specif ifie iess whet whethe herr the the file file form format at is bina binary ry or text text.. Use Use the the stri string ng "b" "b" or "B" to write a binary file. file. Use any other value value to write a text file.
object
Stri String ng
Yes Yes
Cont Contai ains ns the the text text stri string ng or vari variab able le valu valuee cont contai aini ning ng the the data data you want want to write to a file.
Example This example example writes the list of currently logged logged on users to a file. As sample sample data it needs the list of currently logged on users stored in system.users.
function function writeTo writeToFile File( ( path, path, binary, binary, object object ) { prin print( t( "Wri "Writi ting ng " + path path + " to file file.. ..." ." ); var var outp output ut = write writeFil File( e( path, path, binar binary, y, objec object t ); prin print( t( "The "The numb number er of byte bytes s writ writte ten n to file file was: was: " + outp output ut ); return return output; output; } filePath filePath = "C:\\use "C:\\users.x rs.xml"; ml"; isBin isBinary ary = null; null; fileObje fileObject ct = userLis userList; t; writeToF writeToFile ile( ( filePat filePath, h, isBinar isBinary, y, fileObj fileObject ect );
Quit Stops the processing of JavaScript from the point it is called, and returns the failure return code specified in the return code argu code argument. ment. All JavaScript JavaScript code after the Quit() method method call is ignored. The syntax is: Quit( return code ). code ). The following argument is valid for this function: at return code
Inte Intege gerr
Yes Yes
Cont Contai ains ns the the nume numeri ricc retu return rn code code you you want want the the meth metho od to retu return rn..
Example This example prints a message, quits, and returns a failure return code: print print( ( "Tes "Testin ting g the Quit( Quit() ) metho method. d..." .." ); Quit Quit( ( -1 ); print print( ( "You "You won' won't t see see this this messa message ge becau because se the the JavaS JavaScr cript ipt has alrea already dy quit" quit" );
base64Encode Converts Converts binary data data to a base-64 base-64 string format. format. You can also use this method to encode encode plain text data in base-64 base-64 format. format. The method method returns a string string object with the data in base-64 base-64 format. format. The syntax for using this global method is: base64Encode( data ). The following argument is valid for this method: at data
Bina Binary ry
Yes Yes
Cont Contai ains ns the the data data you you want want the the scri script pt to enco encode de in base base-6 -64 4 form format at..
Example This example reads the contents of a binary file, converts the file to a base-64 string format, and prints the base-64 base-64 string. It requires requires a binary binary file on the local file system system (for example, example, an image file) as sample data: var source source = readFil readFile( e( "C:\\he "C:\\header ader _left.gi left.gif", f", "b" ); var encod encode e = base6 base64E 4Enco ncode de( ( sourc source e );
24
prin print( t( "The "The valu value e of enco encode de is:\ is:\n" n" + enco encode de );
base64Decode Converts base-64 string string data to its original format. format. Returns a binary or string string object containing the original original data. The syntax syntax for this method is: base64Decode( data ). The following argument is valid for this method: at data
Bina Binary ry
Yes Yes
Cont Contai ains ns the the data data you you want want the the scri script pt to deco decode de to its its orig origin inal al form format at..
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 source = readFil readFile( e( "C:\\he "C:\\header ader _left.gi left.gif", f", "b" ); var encod encode e = base6 base64E 4Enco ncode de( ( sourc source e ); var encoded encodedFile File = writeFi writeFile( le( "C:\\bas "C:\\base64 e64Enco EncodedI dedImage mage.txt .txt", ", "b", encode encode ); print print( ( "Wro "Wrote te " + encod encoded edFil File e + " bytes bytes to C:\\b C:\\base ase64 64Enc Encod odedI edIma mage. ge.tx txt" t" ); source source = readFil readFile( e( "C:\\bas "C:\\base64 e64Enco EncodedI dedImage mage.tx .txt", t", "t" ); var decod decode e = base6 base64D 4Deco ecode de( ( sourc source e ); var decoded decodedFile File = writeFi writeFile( le( "C:\\new "C:\\newIma Image.g ge.gif", if", "b", decode decode ); print print( ( "Wro "Wrote te " + decod decoded edFil File e + " bytes bytes to C:\\n C:\\newI ewIma mage. ge.gi gif" f" );
xmlstring Converts Converts a JavaScript JavaScript string to an XML-forma XML-formatted tted string. string. Does not return return a value. The syntax syntax is: xmlstring (string (string)) The following argument is valid for this function: at string
Stri String ng
No
Cont Contai ains ns the the text text stri string ng or varia ariabl blee valu valuee you want want the the scri script pt to conv conver ertt to an XML string.
Example var xmldo xmldoc c = new new SCFi SCFile( le( syste system.u m.use sers rs );
doHTTPRequest Sends an HTTP request request to a remote server specified specified by a URL. This method method returns a string containing containing an HTTP response response or an error message. message. The syntax syntax for this method is: doHTTPRequest( HTTP command , URL, URL, Headers, Headers, POST body , Connect timeout , Send timeout , Receive timeout ) timeout ) The following arguments are valid for it: at HTTP command
Str String ing
Yes Yes
Spec Specif ifie iess a comm ommand and verb verb such such as GET or POS POST.
URL
Stri String ng
Yes Yes
Spec Specif ifie iess the the URL URL to whic whichh the the scri script pt shou should ld send send an HTTP HTTP requ reques est. t. If the the HTTP request requires SSL then the URL must start with https.
Headers
Arra Arrayy
Yes Yes
Cont Contai ains ns a Java JavaSc Scri ript pt arra arrayy of Serv Servic icee Manag Manager er-d -def efin ined ed Head Header er obje object ctss or an empty array. See the Header object for for more information. information.
POST body
Str String ing
No
Conta ontaiins the the body body of a POS POST com command and requ reques estt.
Connect timeout
Inte Intege gerr
No
Spec Specif ifie iess the conn connec ectition on time timeou outt thre thresh shol old d in seco second ndss or mill millis isec econ onds ds.. Use positive integers for second thresholds and negative integers for millisecond thresholds. thresholds. Use a value of zero zero for an infinite connection timeout threshold.
Send timeout
Inte Intege gerr
No
Spec Specif ifie iess the send send time timeou outt thre thresh shol old d in seco second ndss or mill millis isec econ onds ds.. U Use se positive integers for second thresholds and negative integers for millisecond thresholds. thresholds. Use a value of zero zero for an infinite connection timeout threshold.
Receive timeout
Inte Intege gerr
No
Spec Specif ifie iess the rece receiv ivee time timeou outt thre thresh shol old d in seco seconds nds or mill millis isec econ onds ds.. Use Use positive integers for second thresholds and negative integers for millisecond thresholds. thresholds. Use a value of zero zero for an infinite connection timeout threshold.
Example This example sends an HTTP request to the Service Manager Web Services API, and writes the response response to a local file. It requires requires the URL to the Service Manager Manager Web Services API as sample data: data: var var var var
doSOAPRequest Issues a SOAP request to a remote server specified by an URL, and returns the SOAP response in a string string or an error message. message. The syntax syntax for this method is: doSOAPRequest( URL, URL, SOAPAction, SOAPAction, XML, XML, SOAP user ID , SOAP password , Connect timeout , Send timeout , Receive timeout , Attachment object )
26
The following arguments are valid for it: at URL
Stri String ng
Yes Yes
Spec Specif ifie iess the the URL URL to whic whichh the the scri script pt shou should ld send send an HTTP HTTP requ reques est. t. IfIf the HTTP request requires SSL, then the URL must start with https.
SOAPAction
String
Yes
Specifies the SOAP request.
XML
Stri String ng
Yes Yes
Cont Contai ains ns the the XML XML for for an enti entire re SOAP SOAP requ reques estt incl includ udin ing g the the SOAP SOAP envelope. Refer to the Web Service's Service's WSDL to determine the proper format of the SOAP request.
SOAP user ID
Stri String ng
No
Cont Contai ains ns the the user user ID to be used sed for for the the Basi Basicc Auth Author oriz izat atio ionn HTTP HTTP header.
SOAP password
Stri String ng
No
Cont Contai ains ns the the pass passwo word rd valu valuee to be used used for for the the Basi Basicc Auth Author oriz izat atio ionn HTTP header.
Connect timeout
Inte Intege gerr
No
Spec Specif ifie iess the conn connec ectition on time timeou outt thre thresh shol old d in seco second ndss or mill millis isec econ onds ds.. Use positive integers for second thresholds and negative integers for millisecond thresholds. thresholds. Use a value of zero zero for an infinite connection timeout threshold.
Send timeout
Inte Intege gerr
No
Spec Specif ifie iess the send send time timeou outt thre thresh shol old d in seco second ndss or mill millis isec econ onds ds.. U Use se positive integers for second thresholds and negative integers for millisecond thresholds. thresholds. Use a value of zero zero for an infinite connection timeout threshold.
Receive timeout
Inte Intege gerr
No
Spec Specif ifie iess the rece receiv ivee time timeou outt thre thresh shol old d in seco seconds nds or mill millis isec econ onds ds.. Use Use positive integers for second thresholds and negative integers for millisecond thresholds. thresholds. Use a value of zero zero for an infinite connection timeout threshold.
Attachment object
Arr Array ay
No
Cont Contai ains ns a Java JavaSc Scrript ipt arra arrayy of Serv Servic icee Mana Manage gerr-defi d efine ned d Atta Attach chme ment nt objects or an empty array. See the Attachment object for more more information.
Example This example sends a SOAP request to a delayed stock quote Web service, and prints the SOAP response response to the screen. It requires requires the following sample sample data:
The URL to a Web-based delayed stock quotation service. The stock symbol for the company.
var url = "http://ws.cdyn "http://ws.cdyne.com/de e.com/delayedst layedstockquote ockquote/delayed /delayedstockqu stockquote.asmx ote.asmx"; "; var action = "http://ws.cdyn "http://ws.cdyne.com/G e.com/GetQuote" etQuote"; ; var xml = " ring\">GOOG ol> tring\">0 seKey> "; var var uid uid = null null; ; var var pass pass = null null; ; var attac attachm hment ents s = new new Array Array() (); ; var quote quote = doSO doSOAPR APReq eques uest( t( url, url, actio action, n, xml, xml, uid, uid, pass pass, , 10, 10, 10, 10, 10, attachme attachments nts ); prin print( t( "The "The retu return rn valu value e is: is: " + quot quote e );
27
makeSCWebURL This method method creates and returns returns a string string containing containing a URL query to the Service Manager Manager Web tier. It does not convert any special characters in the URL (such as spaces or quotation marks) to the characer characer code equivalent equivalent in URL format. format. You can use the encodeURL encodeURL method to convert convert any special special characters in the URL. The syntax is makeSCWebURL( Web tier URL, URL, docEngine , table name , query , hash key seed , action, action, title ) title ) The following arguments are valid for this function: at
Web tier URL
String
Yes
This argument specifies the fully qualified URL to the Service Manager Web tier. This URL must include the http:// protocol syntax as well as the server name or IP address and communications port number.
docEngine
String
Yes
This argument specifies that the query should be handled by the Service Manager Document Engine. This argument does not accept any other string value.
table name
String
Yes
This argument specifies the table where the Document Engine should query for records.
query
String
Yes
This argument specifes the Service Manager query you want to use to search for records. The query should be in the Service Manager server's system language format.
hash key seed String
No
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.
action
String
No
This argument specifies the Document Engine action you want the URL query to perform. By default, the URL query performs a search operation.
title
String
No
This argument specifies the optio tional tit title.
Example This example creates a URL query to the Service Manager Web tier and converts any special characters characters in the URL to valid valid URL format. It requires requires the following sample sample data:
The URL to Service Manager Web tier A valid Service Manager table name (for example, incidents) A valid Service Manager query against the table (for example, incident.id="SD1001")
function function createU createURLqu RLquery( ery( table, table, query, query, title title ) { var var url; url; var webtier webtier; ; var webserver; webserver; var doceng; doceng; var hashkey hashkey; ; var action; action; webserv webserver er = "http:// "http://< /sc/index.do"; doceng doceng = "docEng "docEngine" ine"; ; hashk hashkey ey = ""; ""; acti action on = ""; ""; webtier webtier = makeSCW makeSCWebUR ebURL( L( webserv webserver, er,
28
doceng, table, query, hashkey, action, title title ); print( print( "Creatin "Creating g URL from informat information ion provide provided... d..." " ); print print( ( "The "The value value of webti webtier er is:\n is:\n" " + webti webtier er ); print print( ( "Conv "Convert ertin ing g speci special al chara characte cters rs in URL to valid valid URI URI forma format. t..." .." ); url url = encod encodeU eURI( RI( webti webtier er ); prin print( t( "The "The valu value e of url url is:\ is:\n" n" + url url ); return return url; } var tablena tablename me = "inciden "incidents" ts" var SCquery SCquery = "incide "incident.i nt.id=\" d=\"SD10 SD1001\" 01\"" " var titlena titlename me = "Interac "Interaction tion SD1001" SD1001" createUR createURLqu Lquery( ery( tablenam tablename, e, SCquery SCquery, , titlena titlename me );
help Displays Displays a brief description description of a Service Service Manager-defined Manager-defined JavaScript JavaScript object. Requires Requires the use of the print() print() method to see the help text string. string. Returns Returns a brief text string describing describing the Service ManagerManagerdefined defined JavaScript JavaScript object, or returns null if no help is available. available. The syntax syntax is: help( object ). object ). The following argument is valid for this function:
object
Service Manager-defined JavaScript object
Yes Yes
Cont Contai ains ns the the Serv Servic icee Manag Manager er-d -def efin ined ed Java JavaSc Scri ript pt object for which you want a brief description.
Example This example displays the help contents of several Service Manager-defined JavaScript objects var var f = new new SCFi SCFile le() (); ; prin print( t( help help( ( f ) ); var var x = new new XML( XML(); ); prin print( t( help help( ( x ) ); var var d = new new XMLD XMLDat ate( e(); ); prin print( t( help help( ( d ) );
RCtoString Converts Converts a Service Service Manager Manager global return code value into a localized localized text string. The syntax is: RCtoString( return code ). code ). The following argument is valid for this function: at return code
Inte Intege gerr
Yes Yes
Cont Contai ains ns the the Serv Servic icee Mana Manage gerr glob global al retu return rn code code value alue that that you want want to convert to a localized string.
29
Example This example searches the contacts table for any contact name you define in the search variable, and displays displays the contact contact record as a text string. string. It requires requires the following following sample sample data: A valid contact contact name (such as "FALCON, JENNIFER") and an invalid contact name (such as "NOT A, CONTACT"). var contactName; contactName; function function findCon findContact tactName Name( ( name name ) { prin print( t( "Sea "Searc rchi hing ng for for cont contac act: t: " + name name + "... "..." " ); var var cont contact actLi List st = new SCFil SCFile( e( "cont "contac acts" ts" ); var findCon findContact tact = contactL contactList. ist.doSe doSelec lect( t( "contact "contact.na .name=\ me=\""+ ""+ name + "\"" ) if ( find findCo Cont ntac act t == RC _SUCCESS SUCCESS ) { prin print( t( "Suc "Succe cess ss. . foun found d " + name name + " in cont contac act t reco record rd:\ :\n" n" + contactList.get contactList.getText() Text() ); return contactList; contactList; } else { print print( ( "Coul "Could d not find find conta contact. ct. " + RCtoS RCtoStr tring ing( ( findC findCont ontac act t ) ); return return null; null; } } contactN contactName ame = "FALCON "FALCON, , JENNIFE JENNIFER"; R"; findContactName findContactName( ( contactName contactName ); conta contactN ctNam ame e = "NOT "NOT A, CONTA CONTACT CT"; "; findContactName findContactName( ( contactName contactName );
execute Validates the syntax of a JavaScript and displays the message "Successful compilation of JavaScript function or expression" if the JavaScript JavaScript passes validation; validation; otherwise displays an an error message. The compile() compile() method is an alias of the execute() execute() method. method. The syntax syntax for this method is: execute( script, description ). No throws are defined for it, and the following arguments are valid for it: at script
String
Yes Yes
Contains the the name of the script you want to validate ate.
description
String
No
Use this argument to store any comments you want.
Example This example example creates a variable variable to store store a JavaScript JavaScript name, and validates validates the contents contents of the script. script. It requires a valid JavaScript for sample data: var s = "lib.SC "lib.SCFILE FILEgetT getTextT extTest est"; "; excut excute( e( s, "Test "Testing ing execu execute" te" );
compile Validates the syntax of a JavaScript and displays the message "Successful compilation of JavaScript function or expression" if the JavaScript JavaScript passes validation; validation; otherwise displays an an error message. The compile() compile() method is an alias of the execute() execute() method. method. The syntax syntax for this method is
30
compile( script , description ). No throws are defined defined for compile(). The following following arguments arguments are valid for it: at script
String
Yes Yes
Contains the the name of the script you want to validate ate.
description
String
No
Use this argument to store any comments you want.
Example This example example creates a variable variable to store store a JavaScript JavaScript name, and validates validates the contents contents of the script. script. It requires a valid JavaScript for sample data: var s = "lib.SC "lib.SCFILE FILEgetT getTextT extTest est"; "; compi compile( le( s, "Tes "Testin ting g execut execute" e" );
JavaScript objects Attachment This object is unique to Service Manager and contains attachment data for use with doSOAPRequest methods. methods. You can use the readFile readFile global global method to add data data to the Attachment Attachment object. You can use the push method to add Attachment objects to a JavaScript array. The constructor is: new Attachment(); No arguments arguments are passed passed into the object. object. The following following properties properties are valid for it: at value
Binary
Contains the binary dat data of the att attachm chment.
len
Integer
Contains the length of the binary data in bytes.
href href
Stri String ng
Cont Contai ains ns the the uniq unique ue iden identi tifi fier er for for the the atta attach chme ment nt in the the SOAP SOAP requ reques estt mess messag age. e.
acti action on
Stri String ng
Cont Contai ains ns the the name name of acti action on to take take with with the the atta attach chme ment nt in Serv Servic icee Mana Manage gerr Web Web Services Service Manager Manager API. The following options options are available:
add – Adds the specified attachment.
remove – Removes the specified attachment.
get – Retreives the specified attachment.
update – Updates the specified attachment.
nam name
Strin tring g
Conta ontain inss the the nam name of the the atta attach chm ment, nt, whic whichh is typi typica callly a file ile nam name.
type
String
Contains the MIME type of the attachment.
attachm attachment entTyp Typee
String String
Pertai Pertains ns only only to Servic Servicee Manage Managerr attachm attachment ents, s, and contai contains ns the attachm attachment ent type type as defined in Service Manager. Manager. 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 new Atta Attachm chmen ent() t(); ; var source source = readFil readFile( e( "C:\\he "C:\\header ader _left.gi left.gif", f", "b" ); a.value a.value = source; source; a.name a.name = "C:\\he "C:\\header ader _left.gif";
31
prin rint( "The value of a is: " + a ); print print( ( "Set "Settin ting g attac attachme hment nt value value to sour source: ce: " + a.nam a.name e ); prin print( t( "The "The size size of the the atta attach chme ment nt is: is: " + a.le a.len n + " byte bytes" s" );
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 Header(Header type , Header value ) creates an Header object containing containing the provided header types and values. Always enclose header types and header values in quotation marks. This JavaScript JavaScript object is unique to Service Service Manager. The following following arguments arguments are valid for it:
Header type
The HTTP header type, such as "Accept-Encoding" or "Content-Type".
Header value
The HTTP header value, such as "gzip,deflate" or "text/html".
No properties or methods are defined for this object. Example var h = new new Head Header( er( "Acce "Acceptpt-En Encod codin ing", g", "gzip "gzip,de ,defl flate ate" " ); var var hd = new new Head Header er() (); ; hd.name hd.name = "Content "Content-Ty -Type"; pe"; hd.value hd.value = "text/ht "text/html"; ml"; var heade headers rs = new new Array Array() (); ; headers. headers.pus push( h( hd );
SCFile The SCFile JavaScript JavaScript object is unique to Service Manager. Manager. When called with no parameters, parameters, the SCFile() constructor, new SCFile() creates an empty SCFile object. When called with an object parameter, the SCFile() constructor, new SCFile(object SCFile(object ) creates an SCFile object containing the specified specified record, structure, or array. array. Always enclose table table names and arrays in quotation marks. This object's methods use the the Service Manager-defined global return codes. The following argument argument is valid for this object:
object
String String
The table table name, name, recor record, d, struct structure ure,, or array array you you want want to query query or update update..
No properties properties are defined for this object. object. The following following methods methods are valid for it: Detailed instructions instructions for these these methods can be found in the section section JavaScript methods for the Note: Note: Detailed SCFile objects.
32
Method Name
Description
doActi doAction on
Execut Executes es a method method define defined d on the object object..
doDelete doDelete
Synonymo Synonymous us with the doRemove doRemove method, method, doDelete doDelete simply simply has has a more more intuitive intuitive name.
doIn doInse sert rt
Inse Insert rtss an obje object ct into into the the data databa base se..
doRem doRemove ove
Remove Removess an object object from from the databas database. e.
doSave doSave
Insert Insertss a new record record,, or update updatess an existi existing ng recor record. d.
doSelect doSelect
Makes a query. query. It no no longer longer requires requires that the the first first argument argument be the the name name of of the table if the the object object is constructed with the name of the table.
doUp doUpda date te
Upda Update tess the the data databa base se..
getFir getFirst st
Moves Moves to the first first recor record d if the object object repre represen sents ts a resul resultt set. set.
getLas getLastt
Moves Moves to the last last record record if the object object repres represent entss a resul resultt set. set.
getNex getNextt
Moves Moves to the next next reco record rd if the object object repre represen sents ts a resu resultlt set. set.
getPre getPrevv
Moves Moves to the previo previous us recor record d ifif the the object object repres represent entss a resul resultt set. set.
getS getSiz izee
Retu Return rnss the the size size of the the obje object. ct.
getTex getTextt
Retur Returns ns a text text repre represen sentat tation ion of the object object..
getT getTyype
Retu Return rnss the the obje object ct type type..
getXML getXML
Retur Returns ns an XML repre represen sentat tation ion of the object object..
isReco isRecord rd
Checks Checks whethe whetherr an object object repres represent entss a curren currentt table table and has a reco record. rd.
join join
Retu Return rnss a stri string ng of all all the the entr entrie iess in the the arra array. y.
JSD JSDate ate
Retu Return rnss a Java JavaSc Scri ript pt Date Date obje object ct..
leng length th
Retu Return rnss the the leng length th of the the obje object ct..
pop pop
Rem Removes ves an item item from from an arra arrayy.
pus push
Adds dds an item to an array. ay.
setT setTyype
Sets Sets the the objec bjectt type type..
setV setVal alue ue
Sets Sets the the obje object ct to a give givenn valu value. e.
shif shiftt
Retu Return rnss a stri string ng of all all the the entr entrie iess in the the arra array. y.
toAr toArra rayy
Conv Conver erts ts an obje object ct to a Java JavaSc Scri ript pt arra array. y.
unsh unshif iftt
Retu Return rnss a stri string ng of all all the the entr entrie iess in the the arra array. y.
Example var q = new new SCFi SCFile( le("c "cont ontact acts" s"); ); if ((q.doS ((q.doSelec elect('c t('cont ontact. act.name name # "B"')) "B"')) == RC _SUCCESS) { print(q.getText()); } else { print(" print("Retu Return rn code code is: " + q.RCtoSt q.RCtoString ring); ); }
33
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 not use the Service Manager-def Manager-defined ined global global return codes. The XML JavaScript JavaScript object object is unique unique to Service Manager. Manager. No properties properties are defined for the method, method, and it accepts accepts no arguments. arguments. The following following methods are valid for this object. Detailed instructions instructions for these these methods can be found in the section section JavaScript methods for the Note: Note: Detailed XML object . dN addA addAttr ttrib ibut utee
Inse Insert rtss an XML XML attr attrib ibut utee and and attri attribu bute te valu valuee into into the the curr curren entt elem elemen ent. t.
addE addEle leme ment nt
Inse Insert rtss an XML XML elem elemen entt as a chil child d of the the curr curren entt elem elemen ent. t.
appe append ndNo Node de
Inse Insert rtss an XML node node int into an XML obje bject. ct.
crea create teN Node
Crea Create tess an XML XML node node from from an XML obje bject. ct.
getA getAttr ttrib ibut uteN eNod odee
Retu Return rnss an XML XML obje object ct cont contai aini ning ng an attr attrib ibut utee node node..
getA getAttr ttrib ibut uteV eVal alue ue
Retu Return rnss the the valu valuee of the the targe targett attri attribu bute te..
getDocume getDocumentEle ntElement ment
Creates Creates an XML object object containing containing the document document element element and all child elements elements from an XML object or XML string.
getFir getFirstA stAttr ttribu ibute te
Return Returnss an XML object object repres represent enting ing the first first attribu attribute te of the curren currentt node. node.
getFirstChi getFirstChildEl ldElemen ementt
Returns Returns an XML object object represent representing ing the first child child node of the current current node.
getN getNam amee
Retu Return rnss a stri string ng repr repres esen enti ting ng the the name name of the the curr curren entt elem elemen entt or attr attrib ibut ute. e.
getNex getNextAt tAttri tribut butee
Return Returnss an XML object object repres represent enting ing the next next attrib attribute ute of the curren currentt node. node.
getNextSi getNextSibling blingElem Element ent
Returns Returns an an XML XML object object represent representing ing the next next node at the same level level in in the the Docume Document nt Object Model (DOM) tree as the current node.
getN getNod odeN eNam amee
Retu Return rnss a stri string ng repr repres esen entiting ng the the name name of the the curr curren entt elem elemen entt or attr attrib ibut ute. e.
getN getNod odeT eTyp ypee
Eval Evalua uate tess an XML XML obje object ct and and retu return rnss an inte intege gerr repr repres esen entiting ng the the XML XML Docu Docume ment nt Obje Object ct Model (DOM) type of the current element or attribute.
getN getNod odeV eVal alue ue
Retu Return rnss a stri string ng repr repres esen entiting ng the the valu valuee of the the curr curren entt elem elemen ent. t.
getP getPar aren entN tNod odee
Retu Return rnss an XML XML obje object ct repr repres esen entiting ng the the paren parentt node node of the the curr curren entt node node..
getP getPre refi fixx
Retu Return rnss a stri string ng repr repres esen entiting ng the the name namesp space ace valu valuee of the the curr curren entt elem elemen entt or attr attrib ibut ute. e.
getQu getQuali alifie fiedNa dName me
Return Returnss a string string repres represent enting ing the name name of of the the curren currentt elem element ent or attribu attribute te inclu includin ding g any namespace value.
getT getTex extt
Retu Return rnss a str string ing repr repreesent sentin ing g the the valu alue of the the cur current rent elem elemen ent. t.
getV getVal alue ue
Retu Return rnss a stri string ng repr repres esen enti ting ng the the valu valuee of the the curr curren entt elem elemen ent. t.
impo import rtN Node ode
Copi Copies es an XML XML node node from from one one XML docu docume ment nt to anot anothe her. r.
isDocu isDocume mentE ntElem lement ent
Return Returnss true true if the curren currentt elemen elementt is the Docum Document ent Object Object Model Model (DOM) (DOM) docum document ent element.
setA setAttttri ribu bute teVa Valu luee
Adds Adds or upda update tess an attri attribu bute te valu value. e.
setC setCo onten ntentt
Crea Create tess an XML XML docu docum ment ent from rom a strin tring g or file. ile.
setN setNod odeV eVal alue ue
Adds Adds or upda update tess the the value alue of the the curr curren entt elem elemen ent. t.
setText
Adds or updat dates the valu alue of the the current element.
setValu alue
Adds or updates the valu alue of the the current element.
34
dN toXM toXMLS LStr trin ing g
Conv Conveerts rts an XML obje bject into into a val valid XML str string. ing.
Example /* Insta Instant ntiat iate e an empty empty XML objec object t */ var var xmlO xmlObj bj = new new XML( XML(); ); /* Inst Instan anti tiat ate e a vari variab able le cont contai aini ning ng the the path path to an XML XML file file */ var xmlFile xmlFile = "C:\\my "C:\\myxmld xmldoc.x oc.xml"; ml"; /* Use Use setC setCon onte tent nt to make make the the XML XML obje object ct read read and and pars parse e the the XML XML file file * If the the setC setCon onte tent nt meth method od fail fails, s, prin print t an erro error r mess messag age e */ if ( ! xmlO xmlObj. bj.se setCo tCont ntent ent( ( xmlF xmlFile ile, , true true ) ) { print print( ( "setC "setCont onten ent t faile failed. d. Unabl Unable e to parse parse xml: xml: " + xmlF xmlFile ile ); }
XMLDate The XMLDate XMLDate JavaScript JavaScript object is unique to Service Manager. It has no arguments, arguments, and the XMLDate() constructor, new XMLDate() creates an empty XMLDate object. When used with a DateObject argument, DateObject argument, the XMLDate() constructor, new XMLDate(DateObject XMLDate(DateObject ) converts a JavaScript date object to an XMLDate object. When used with an ISO8601DateTimeOrDurationString argument, the XMLDate() constructor, new XMLDate(ISO8601DateTimeOrDurationString XMLDate(ISO8601DateTimeOrDurationString)) converts an XML schema date object to an XMLDate object. When used with a DateTimeDatum argument, the XMLDate() constructor, new XMLDate(DateTimeDatum XMLDate(DateTimeDatum)) converts a Service Manager date object to an XMLDate object. This object's methods use the the Service Manager-defined global return codes. The following arguments arguments are valid for this object:
DateObject
JavaScript date object
Passes a JavaScript date object to the XMLDate constructor.
ISO8601DateTimeOrDurationString
XML schema schema date date
Passes Passes an XML schema schema date, date, time, time, datetim datetime, e, or durati duration on string to the XMLDate constructor.
DateTimeDatum
Service Manager Datum object
Passes a Service Manager 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, getMonth, getDate and getYear methods, methods, December 31st 2005 would be represented as 11-31-105.
35
Seconds and minutes
0 through 59
Hours
0 through 23
Da y
0 through 6 (day of the week)
Date
1 through 31 (day of the month)
Months
0 (January) through 11 (December)
Year
Number of years since 1900
No properties properties are defined for the XMLDate XMLDate object. The following following methods methods are valid for it: Detailed instructions instructions for these these methods can be found in the section section JavaScript methods for the Note: Note: Detailed XMLDate object .
Adds the indicated duration to the contained value in the XMLDate object.
getDate
Returns a JavaScript date object (same as the JSDate method).
getDatum
Returns an SCFile object
getG getGMT MTSC SCDa Date teTi Time meSt Stri ring ng
Retu Return rnss the the Gree Greenw nwic ichh Mean Mean Time Time (GMT (GMT)) date date time time in Serv Servic icee Manager format.
getISODate
Returns the indicated portions of the XMLDate value.
getI getISO SODa DatteTim eTimeS eStr trin ing g
Pas Passes ses a JavaS avaScr criipt Date ate objec bjectt to the con constru struct ctor or..
getISODay
Returns the indicated portions of the XMLDate value.
getISOMonth
Returns the indicated portions of the XMLDate value.
getISOTime
Returns the indicated portions of the XMLDate value.
getISOYear
Returns the indicated portions of the XMLDate value.
getS getSC CDate DateTi Tim meStr eStrin ing g
Retu Returrns a dat date time time stri string ng in Serv ervice ice Manag anager er for format. at.
JSDate toSCDuration
Returns a Javascript date object. Converts an ISO duration string to a Service Manager duration.
Example /* Inst Instan anti tiat ate e a new new SCFi SCFile le obje object ct with with reco record rds s of the the cm3r cm3r tabl table e */ var changeR changeReque equest st = new SCFile(" SCFile("cm3 cm3r"); r"); /* Set Set the the Servi Service ce Manag Manager er field fields s date. date.ent enter ered ed and and plann planned ed.st .star art t to today's today's date. date. * The The dots dots in Servi Service ce Mana Manage ger r fiel field d name names s must must be conv conver erte ted d to undersco underscores res */ var theXM theXMLD LDate ate = new new XMLDat XMLDate( e( new Date( Date() ) ); var todaysD todaysDate ate = theXMLD theXMLDate. ate.getD getDatu atum(); m(); changeRequest.header.date _entered entered = todaysD todaysDate; ate; changeRequest.header.planned _start start = todaysD todaysDate; ate; /* * * *
Incr Increm emen ent t the the valu value e of the the plan planne ned. d.en end d fiel field d to be a week week late later. r. P is the the addD addDur urat atio ion n para parame mete ter r for for dura durati tion on 7D is the the addD addDur urat atio ion n para parame mete ter r for for 7 days days See See the the addDu addDurat ratio ion n metho method d for additi additiona onal l inform informat ation ion */
JavaScript methods for the SCFile objects SCFile.doAction() This method executes a Document Engine action using any new field values defined in a Service Manager Manager file object. It requires requires that you define a Service Service Manager file object, 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: at docEngineAction
String String
Specif Specifies ies the Docum Document ent Engine Engine action action you want the script script to execu execute te on the object object.. Must Must contain a valid Service Manager Document Engine action appropriate for the Service Manager object.
Example This example example creates a new incident record from variable variable values, values, and resolves 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. funct function ion inser insertI tInci ncide dent( nt( num, num, name, name, cat, cat, desc desc ) { print( print( "Creatin "Creating g new incident incident record. record..." .." ); var var newI newInci ncide dent nt = new SCFil SCFile( e( "prob "probsu summa mmary ry" " ); newInci newIncident dent.num .number ber = num; newIncident.callback _conta contact ct = name; name; newInci newIncident dent.cat .catego egory ry = cat; cat; newIncident.des newIncident.descriptio cription n = desc; var rc = newInci newIncident dent.doI .doInse nsert() rt(); ; i f ( r c = = R C _SUCCESS SUCCESS ) { print print( ( "Succ "Succes ess. s. Creat Created ed new new recor record d " + newIncident.get newIncident.getText() Text() ); return newIncident.num newIncident.number; ber; } else { prin print( t( "Cou "Could ld not not crea create te reco record rd. . " + RCto RCtoSt Stri ring ng( ( rc ) ); return return null; null; } } function function closeIn closeIncide cident( nt( id, action, action, rescode rescode, , res ) { prin print( t( "Res "Resol olvi ving ng inci incide dent nt " + id + "... "..." " ); var var find findInc Incid ident ent = new new SCFi SCFile le ( "prob "probsum summar mary" y" );
37
var var f = findI findInci ncide dent. nt.doS doSel elect ect( ( "numb "number= er=\" \"" " + id + "\"" "\"" ); i f ( f = = R C _SUCCESS SUCCESS ) { print( print( "Succes "Success. s. Found Found iteracti iteraction on record.. record..." ." ); findIncident.resolution _code code = resco rescode de; ; findIncident.re findIncident.resolution solution = res; var a = findI findInci ncide dent. nt.do doAct Actio ion( n( actio action n ); print print( ( "The "The resol resolve ve Inci Inciden dent t retur return n value value is " + RCto RCtoSt Stri ring ng( ( a ) ); print print( ( "The "The incid inciden ent t recor record d is " + findI findInc ncide ident nt.ge .getT tText ext() () ); prin print( t( "The "The valu value e of the the stat status us fiel field d is: is: " + findIncident.problem _statu status s ); return findIncident; findIncident; } else { prin print( t( "Cou "Could ld not not find find reco record rd. . " + RCto RCtoSt Stri ring ng( ( f ) ); return return null; null; } } var numberV numberValue alue = "IM1111 "IM11112"; 2"; var callbac callbackCon kContact tact = "FALCON "FALCON, , JENNIFE JENNIFER"; R"; var categor categoryVal yValue ue = "network "network"; "; var descrip description tionValu Value e = null; null; var interac interaction tionID ID = insertIn insertIncide cident( nt( numberV numberValue alue, , callback callbackCont Contact act, , categoryValue, categoryValue, descriptionValu descriptionValue e ); var actionT actionType ype = "resolv "resolve"; e"; var resulti resultionCo onCodeVa deValue lue = "Advice "Advice & Guidance Guidance"; "; var resolut resolutionV ionValue alue = null; null; closeIncident( closeIncident( interactionID, interactionID, actionType, actionType, resultionCodeVa resultionCodeValue, lue, resolutionValue resolutionValue );
SCFile.doDelete() This method removes a Service Manager record with any new field values defined in a Service Manager Manager file object. It requires requires that you define both a Service Manager file object and new values values for fields. fields. It is a synonym of the doRemove() doRemove() method. 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, variable, and removes removes the interaction interaction record. It requires requires as sample data a valid value such as "IM11111" in the number field. function function removeI removeInter nteracti action( on( num ) { print( print( "Removin "Removing g interact interaction ion record. record..." .." ); var interac interaction tionRec Record ord = new SCFile( SCFile( "probsum "probsummary mary" " ); var findRec findRecord ord = interact interactionR ionReco ecord.d rd.doSel oSelect( ect( "number= "number=\"" \"" + num + "\""); print print( ( "The "The inter interact actio ion n recor record d is " + inter interac actio tionR nReco ecord rd ); var rc = interac interaction tionReco Record. rd.doDe doDelete lete(); ();
38
i f ( r c = = R C _SUCCESS SUCCESS ) { print( print( "Succes "Success. s. Removed Removed record record " + interac interaction tionReco Record.g rd.getT etText( ext() ) ); return interactionReco interactionRecord; rd; } else { prin print( t( "Cou "Could ld not not remo remove ve reco record rd. . " + RCto RCtoSt Stri ring ng( ( rc ) ); return return null; null; } } var numberV numberValue alue = "IM1111 "IM11111"; 1"; removeInteracti removeInteraction( on( numberValue numberValue );
SCFile.doInsert() This method creates a Service Manager record with any new field values defined in a Service Manager Manager file object. It requires requires that you define both a Service Manager file object and new values values for fields. fields. The syntax syntax for this method 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")
funct function ion inser insertC tCont ontac act( t( num, num, name, name, cat ) { print( print( "Creatin "Creating g new interact interaction ion record. record..." .." ); var newInte newInteract raction ion = new SCFile( SCFile( "probsu "probsummar mmary" y" ); newInteraction. newInteraction.number number = num; newInteraction.callback _conta contact ct = name; name; newInteraction. newInteraction.categor category y = cat; var rc = newInte newInteract raction. ion.doI doInser nsert(); t(); i f ( r c = = R C _SUCCESS SUCCESS ) { print print( ( "Succ "Succes ess. s. Creat Created ed new new recor record d " + newInteraction. newInteraction.getText( getText() ) ); return newInteraction; newInteraction; } else { prin print( t( "Cou "Could ld not not crea create te reco record rd. . " + RCto RCtoSt Stri ring ng( ( rc ) ); return return null; null; } } var numberV numberValue alue = "IM1111 "IM11112"; 2";
39
var callbac callbackCon kContact tact = "FALCON "FALCON, , JENNIFE JENNIFER"; R"; var categor categoryVal yValue ue = "network "network"; "; var insertContact( insertContact( numberValue, numberValue, callbackContact callbackContact, , categoryValue, categoryValue, descriptionValu descriptionValue e );
SCFile.doRemove() This method removes a Service Manager record with any new field values defined in a Service Manager Manager file object. It requires requires that you define both a Service Manager file object and new values values for fields. fields. The syntax syntax for this method 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, variable, and removes the interaction interaction record. It requires a valid value such as "IM11111 "IM11111"" for the number field as sample data: function function removeI removeInter nteracti action( on( num ) { print( print( "Removin "Removing g interact interaction ion record. record..." .." ); var interac interaction tionRec Record ord = new SCFile( SCFile( "probsum "probsummary mary" " ); var findRec findRecord ord = interact interactionR ionReco ecord.d rd.doSel oSelect( ect( "number= "number=\"" \"" + num + "\""); print print( ( "The "The inter interact actio ion n recor record d is " + inter interac actio tionR nReco ecord rd ); var rc = interac interaction tionReco Record. rd.doRe doRemove move(); (); i f ( r c = = R C _SUCCESS SUCCESS ) { print print( ( "Succ "Succes ess. s. Remov Removed ed reco record rd " + interactionReco interactionRecord.getTe rd.getText() xt() ); return interactionReco interactionRecord; rd; } else { prin print( t( "Cou "Could ld not not remo remove ve reco record rd. . " + RCto RCtoSt Stri ring ng( ( rc ) ); return return null; null; } } var numberV numberValue alue = "IM1111 "IM11111"; 1"; removeInteracti removeInteraction( on( numberValue numberValue );
SCFile.doSave() This method adds to or updates the Service Manager database with any new field values defined in a Service Service Manager file object. It requires requires that you define both a Service Manager file object and new values for fields. The syntax is doSave() No arguments are passed.
40
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 Service Manager 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")
function function updateC updateConta ontact( ct( name ) { prin print( t( "Sea "Searc rchi hing ng for for cont contac act: t: " + name name + "... "..." " ); var var cont contact actLi List st = new SCFil SCFile( e( "cont "contac acts" ts" ); var isConta isContact ct = contactL contactList ist.doS .doSelec elect( t( "contac "contact.na t.name=\ me=\""+ ""+ name name + "\"" ); if ( isCo isCont ntac act t == RC _SUCCESS SUCCESS ) { prin print( t( "Suc "Succe cess ss. . foun found d " + name name + " in cont contac act t reco record rd:\ :\n" n" + contactList.get contactList.getText() Text() ); print print( ( "The "The curre current nt cont content ents s of the the user. user.ty type pe field field are: are: " + contactList.user _type type ); print( print( "Updati "Updating ng the user.ty user.type pe field.. field..." ." ); contactList.user _type type = "sit "site"; e"; print( print( "Saving "Saving record. record..." .." ); var rc = contactL contactList. ist.doS doSave( ave(); ); prin print( t( "The "The retu return rn code code valu value e for for the the doSa doSave ve() () meth method od is: is: " + RCtoS RCtoStri tring ng( ( rc ) ); prin print( t( "The "The cont conten ents ts of the the user user.t .typ ype e fiel field d are are now: now: " + contactList.user _type type ); return contactList; contactList; } else { print print( ( "Coul "Could d not find find conta contact. ct. " + RCtoS RCtoStr tring ing( ( isCon isContac tact t ) ); return return null; null; } } var contact contactName Name = "FALCON "FALCON, , JENNIFE JENNIFER"; R"; updateContact( 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 cannot return any records. records. The SCFile object that is returned returned after successful successful query execution execution has the following format:
41
table={ ["field value",{"array value_1","array value_2",,.array value_ n..} ] } The syntax is doSelect( "query "query " ) The following argument is valid for this method:
query
String String
Specif Specifies ies the query query you you want want to use use to to sear search ch for for Servic Servicee Mana Manager ger record records. s. Preced Precedee spec special ial 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")
function function findCon findContact tactName Name( ( name name ) { prin print( t( "Sea "Searc rchi hing ng for for cont contac act: t: " + name name + "... "..." " ); var var cont contact actLi List st = new SCFil SCFile( e( "cont "contac acts" ts" ); var findCon findContact tact = contactL contactList. ist.doSe doSelec lect( t( "contact "contact.na .name=\ me=\""+ ""+ name + "\"" ); if ( find findCo Cont ntac act t == RC _SUCCESS SUCCESS ) { prin print( t( "Suc "Succe cess ss. . foun found d " + name name + " in cont contac act t reco record rd:\ :\n" n" + contactList.get contactList.getText() Text() ); return contactList; contactList; } else { print print( ( "Coul "Could d not find find conta contact. ct. " + RCtoS RCtoStr tring ing( ( findC findCont ontac act t ) ); return return null; null; } } var contact contactName Name = "FALCON "FALCON, , JENNIFE JENNIFER"; R"; findContactName findContactName( ( contactName contactName ); conta contactN ctNam ame e = "NOT "NOT A, CONTA CONTACT CT"; "; findContactName findContactName( ( contactName contactName );
SCFile.doUpdate() This method updates a Service Manager record with any new field values defined in a Service Manager Manager file object. This method method requires requires that you define both a Service Manager file object and new values for fields. The syntax for this method is doUpdate() No arguments are passed.
42
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") A valid field value update (for example, set the user.type field to "site")
function function updateC updateConta ontact( ct( name ) { prin print( t( "Sea "Searc rchi hing ng for for cont contac act: t: " + name name + "... "..." " ); var var cont contact actLi List st = new SCFil SCFile( e( "cont "contac acts" ts" ); var isConta isContact ct = contactL contactList ist.doS .doSelec elect( t( "contac "contact.na t.name=\ me=\""+ ""+ name name + "\"" ); if ( isCo isCont ntac act t == RC _SUCCESS SUCCESS ) { prin print( t( "Suc "Succe cess ss. . foun found d " + name name + " in cont contac act t reco record rd:\ :\n" n" + contactList.get contactList.getText() Text() ); print print( ( "The "The curre current nt cont content ents s of the the user. user.ty type pe field field are " + contactList.user _type type ); print( print( "Updati "Updating ng the user.ty user.type pe field.. field..." ." ); contactList.user _type type = "sit "site"; e"; contactList.doUpdate(); prin print( t( "The "The cont conten ents ts of the the user user.t .typ ype e fiel field d are are now now " + contactList.user _type type ); return contactList; contactList; } else { print print( ( "Coul "Could d not find find conta contact. ct. " + RCtoS RCtoStr tring ing( ( isCon isContac tact t ) ); return return null; null; } } var contact contactName Name = "FALCON "FALCON, , JENNIFE JENNIFER"; R"; updateContact( updateContact( contactName );
SCFile.getFirst() This method method returns the first record record in a record list stored stored in a SCFile object. It requires 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 a 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.
43
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")
function function findFir findFirstCo stContac ntact( t( query query ) { print print( ( "Sear "Searchi ching ng for conta contacts cts start starting ing with with " + query query + "... "..." " ); var var cont contact actFi File le = new SCFil SCFile( e( "cont "contac acts" ts" ); var findCon findContact tact = contactF contactFile. ile.doSe doSelec lect( t( "contact "contact.na .name#\ me#\""+ ""+ query query + "\"" "\"" ); if ( find findCo Cont ntac act t == RC _SUCCESS SUCCESS ) { prin print( t( "Suc "Succe cess ss. . Foun Found d cont contac acts ts star starti ting ng with with " + quer query y + "." "." ); var findLastRecord findLastRecord = contactFile.get contactFile.getLast(); Last(); print print( ( "The "The last last recor record d is:\n is:\n" " + conta contactF ctFil ile e ); var findPrevRecord findPrevRecord = contactFile.get contactFile.getPrev(); Prev(); print print( ( "The "The previ previou ous s recor record d is:\n is:\n" " + conta contactF ctFil ile e ); var findFirstRecord findFirstRecord = contactFile.get contactFile.getFirst(); First(); print print( ( "The "The first first recor record d is:\ is:\n" n" + contac contactF tFile ile ); } else { prin print( t( "Cou "Could ld not not find find cont contac acts ts star starti ting ng with with " + quer query y + ". " + RCtoStri RCtoString( ng( findCon findContact tact ) ); return return null; null; } } var conta contact ctQue Query ry = "H"; "H"; findFirstContac findFirstContact( t( contactQuery contactQuery );
SCFile.getLast() This method method returns the last record record in a record list stored stored in a SCFile object. object. It requires requires the use of the other SCFile methods to create a record list. The syntax syntax of this method is getLast(). getLast(). No arguments arguments are passed. passed. The method method returns a SCFile object 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")
function function findLas findLastCon tContact tact( ( query query ) {
44
print print( ( "Sear "Searchi ching ng for conta contacts cts start starting ing with with " + query query + "... "..." " ); var var cont contact actFi File le = new SCFil SCFile( e( "cont "contac acts" ts" ); var findCon findContact tact = contactF contactFile. ile.doSe doSelec lect( t( "contact "contact.na .name#\ me#\""+ ""+ query query + "\"" "\"" ); if ( find findCo Cont ntac act t == RC _SUCCESS SUCCESS ) { prin print( t( "Suc "Succe cess ss. . Foun Found d cont contac acts ts star starti ting ng with with " + quer query y + ". The The first first recor record d is:\n is:\n" " + conta contact ctFil File e ); var findLastRecord findLastRecord = contactFile.get contactFile.getLast(); Last(); print print( ( "The "The last last recor record d is:\n is:\n" " + conta contactF ctFil ile e ); return contactFile; contactFile; } else { prin print( t( "Cou "Could ld not not find find cont contac acts ts star starti ting ng with with " + quer query y + ". " + RCtoStri RCtoString( ng( findCon findContact tact ) ); return return null; null; } } var conta contact ctQue Query ry = "H"; "H"; findLastContact findLastContact( ( contactQuery contactQuery ); contactQ contactQuer uery y = "F"; findLastContact findLastContact( ( contactQuery contactQuery );
SCFile.getNext() This method method returns the next record in a record list stored in a SCFile object. It requires requires the use of the other SCFile SCFile methods to create create a record list. The syntax syntax of this method is getNext() No arguments are passed. The method returns a 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")
function function findNex findNextCon tContact tact( ( query query ) { print print( ( "Sear "Searchi ching ng for conta contacts cts start starting ing with with " + query query + "... "..." " ); var var cont contact actFi File le = new SCFil SCFile( e( "cont "contac acts" ts" ); var findCon findContact tact = contactF contactFile. ile.doSe doSelec lect( t( "contact "contact.na .name#\ me#\""+ ""+ query query + "\"" "\"" ); if ( find findCo Cont ntac act t == RC _SUCCESS SUCCESS ) { prin print( t( "Suc "Succe cess ss. . Foun Found d cont contac acts ts star starti ting ng with with " + quer query y + ". The The first first record record is:\n" is:\n" + contact contactFile File.get .getTex Text() t() );
45
var findNextRecord findNextRecord = contactFile.get contactFile.getNext(); Next(); print( print( "The "The next record record is:\n" is:\n" + contactF contactFile. ile.get getText Text() () ); return contactFile; contactFile; } else { prin print( t( "Cou "Could ld not not find find cont contac act t " + quer query y + ". " + RCto RCtoSt Stri ring ng( ( findC findCont ontac act t ) ); return return null; null; } } var conta contact ctQue Query ry = "B"; "B"; findNextContact findNextContact( ( contactQuery contactQuery ); contactQ contactQuer uery y = "F"; findNextContact findNextContact( ( contactQuery contactQuery );
SCFile.getPrev() This method method returns the previous previous record in a record record list stored in an SCFile object. It requires requires that you use the other SCFile SCFile methods to create create a record list. The syntax syntax is getPrev(). getPrev(). No arguments arguments are passed. The method returns a 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. function function findPre findPrevCon vContact tact( ( query query ) { print print( ( "Sear "Searchi ching ng for conta contacts cts start starting ing with with " + query query + "... "..." " ); var var cont contact actFi File le = new SCFil SCFile( e( "cont "contac acts" ts" ); var findCon findContact tact = contactF contactFile. ile.doSe doSelec lect( t( "contact "contact.na .name#\ me#\""+ ""+ query query + "\"" "\"" ); if ( find findCo Cont ntac act t == RC _SUCCESS SUCCESS ) { prin print( t( "Suc "Succe cess ss. . Foun Found d cont contac acts ts star starti ting ng with with " + quer query y + ". The The first first reco record rd is:\n is:\n" " + conta contact ctFil File e ); var findLastRecord findLastRecord = contactFile.get contactFile.getLast(); Last(); print print( ( "The "The last last recor record d is:\n is:\n" " + conta contactF ctFil ile e ); var findPrevRecord findPrevRecord = contactFile.get contactFile.getPrev(); Prev(); print print( ( "The "The previ previou ous s recor record d is:\n is:\n" " + conta contactF ctFil ile e ); } else { prin print( t( "Cou "Could ld not not find find cont contac acts ts star starti ting ng with with " + quer query y + ". " + RCtoStri RCtoString( ng( findCon findContact tact ) ); return return null; null; } }
46
var conta contact ctQue Query ry = "H"; "H"; findPrevContact findPrevContact( ( contactQuery contactQuery );
SCFile.getSize() This method returns the number of array elements in an array stored in a Service Manager SCFile object. object. You can use this method to return the length length of Service Service Manager array array fields, which are always always stored as SCFile objects. objects. To query a particular particular array field in a SCFile object, object, you can use the following format: SCFile_object .array_field_name .getSize() .getSize() Replace any periods in the name of array_field_name with array_field_name with underscores underscores.. For example, example, you convert the Service Manager 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 Service Manager 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 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 Service Manager array data). Displays the size of the action field using the Service Manager getSize() method. Converts the SCFile object into a JavaScript array using the Service Manager 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". function function findInc findInciden idents( ts( query query ) { print print( ( "Sear "Searchi ching ng for incid incident ent recor records ds start startin ing g with with " + quer query y + "..." "..." ); var var inci inciden dentF tFile ile = new new SCFi SCFile( le( "prob "probsum summa mary" ry" ); var findInc findInciden ident t = inciden incidentFil tFile.do e.doSel Select( ect( "number# "number#\""+ \""+ query query + "\"" "\"" ); if ( find findIn Inci cide dent nt == RC _SUCCESS SUCCESS ) { print print( ( "Succ "Succes ess. s. Found Found incid incident ent recor records ds start startin ing g with with " + query query + ". The The firs first t recor record d is:\n is:\n" " + incid incident entFi File le ); var objectSi objectSize ze = inciden incidentFil tFile.ge e.getSiz tSize(); e(); print print( ( "Runn "Runnin ing g the the getS getSize ize() () meth method od on the the retu returne rned d SCFil SCFile e objec object t produ produces ces the the follo followi wing ng resul result: t: " + objec objectSi tSize ze ); var actionTe actionText xt = inciden incidentFil tFile.ac e.action tion; ; print print( ( "The "The conte content nts s of the actio action n field field is:\n is:\n" " + actio actionT nText ext ); var actionSize actionSize = incidentFile.ac incidentFile.action.get tion.getSize(); Size(); prin print( t( "The "The size size of the the acti action on fiel field d is: is: " + acti action onSi Size ze ); print print( ( "Conv "Conver ertin ting g the SCFil SCFile e obje object ct to a JavaS JavaScri cript pt array array... ..." " ); var incidentArray incidentArray = incidentFile.t incidentFile.toArray() oArray(); ; print print( ( "The "The new new JavaS JavaScr cript ipt array array is:\n is:\n" " + incid incident entAr Array ray ); var arraySiz arraySize e = inciden incidentArr tArray.l ay.leng ength; th;
47
prin print( t( "The "The size size of the the conv conver erte ted d arra array y is: is: " + arra arrayS ySiz ize e ); return incidentFile; incidentFile; } else { print print( ( "Coul "Could d not find find incid incident ent recor records ds start startin ing g with with " + query query + ". " + RCto RCtoStr Strin ing( g( findI findInci ncide dent nt ) ); return return null; null; } } var inciden incidentQue tQuery ry = "IM1005" "IM1005"; ; findIncidents( findIncidents( incidentQuery incidentQuery );
SCFile.getText() This method method returns a text string of the current SCFile object. object. The text string has the following following format: 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. Example This example searches the contacts table for any contact name you define in the search variable, and displays displays the contact record as a text string. string. It requires the following following sample data:
A valid contact name (for example, "FALCON, JENNIFER") A invalid contact name (for example, "NOT A, CONTACT")
function function findCon findContact tactName Name( ( name name ) { prin print( t( "Sea "Searc rchi hing ng for for cont contac act: t: " + name name + "... "..." " ); var var cont contact actLi List st = new SCFil SCFile( e( "cont "contac acts" ts" ); var findCon findContact tact = contactL contactList. ist.doSe doSelec lect( t( "contact "contact.na .name=\ me=\""+ ""+ name + "\"" ) if ( find findCo Cont ntac act t == RC _SUCCESS SUCCESS ) { prin print( t( "Suc "Succe cess ss. . foun found d " + name name + " in cont contac act t reco record rd:\ :\n" n" + contactList.get contactList.getText() Text() ); return contactList; contactList; } else { print print( ( "Coul "Could d not find find conta contact. ct. " + RCtoS RCtoStr tring ing( ( findC findCont ontac act t ) ); return return null; null; } } var contact contactName Name = "FALCON "FALCON, , JENNIFE JENNIFER"; R"; findContactName findContactName( ( contactName contactName ); conta contactN ctNam ame e = "NOT "NOT A, CONTA CONTACT CT"; ";
SCFile.getType() This method returns the data type of Service Manager SCFile objects such as arrays and structured arrays. It fails on any scalar fields within file records, such as number, date, string, and Boolean Boolean fields. fields. To determine determine the type of scalar fields you can use, use the core JavaScript JavaScript ".type" property. 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: function function findTyp findTypes( es( query query ) { print print( ( "Sear "Searchi ching ng for incid incident ent recor records ds start startin ing g with with " + quer query y + "..." "..." ); var var inci inciden dentF tFile ile = new new SCFi SCFile( le( "prob "probsum summa mary" ry" ); var findInc findInciden ident t = inciden incidentFil tFile.do e.doSel Select( ect( "number# "number#\""+ \""+ query query + "\"" "\"" ); if ( find findIn Inci cide dent nt == RC _SUCCESS SUCCESS ) { print print( ( "Succ "Succes ess. s. Found Found incid incident ent recor records ds start startin ing g with with " + query query + ". The The firs first t recor record d is:\n is:\n" " + incid incident entFi File le ); var objectTy objectType pe = inciden incidentFil tFile.ge e.getTyp tType(); e(); print print( ( "The "The objec object t incid incident entFi File le is of type: type: " + objec objectTy tType pe ); var arrayFie arrayField ld = inciden incidentFil tFile.ac e.action tion; ; print print( ( "The "The conte content nts s of the actio action n field field are:\ are:\n" n" + array arrayFi Field eld ); fieldType fieldType = arrayField.getT arrayField.getType(); ype(); prin print( t( "The "The type type of the the acti action on fiel field d is: is: " + fiel fieldT dTyp ype e ); var textFiel textField d = inciden incidentFil tFile.ca e.categ tegory; ory; print print( ( "The "The conte content nts s of the categ category ory field field are:\ are:\n" n" + textF textFiel ield d ); fieldTyp fieldType e = textFie textField.t ld.type; ype; prin print( t( "The "The type type of the the cate catego gory ry fiel field d is: is: " + fiel fieldT dTyp ype e ); } else { print print( ( "Coul "Could d not find find incid incident ent recor records ds start startin ing g with with " + query query + ". " + RCto RCtoStr Strin ing( g( findI findInci ncide dent nt ) ); return return null; null; }
49
} var inciden incidentQue tQuery ry = "IM1001" "IM1001"; ; findType findTypes( s( incident incidentQuer Query y );
SCFile.getXML() This method method returns an XML object representat representation ion of the current SCFile object. The XML object has the following format, which is compatible with the Service Manager Systems Web Services API: key value ... >...instance value ... >... 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")
function function findCon findContact tact( ( name name ) { prin print( t( "Sea "Searc rchi hing ng for for cont contac act: t: " + name name + "... "..." " ); var var cont contact actLi List st = new SCFil SCFile( e( "cont "contac acts" ts" ); var isConta isContact ct = contactL contactList ist.doS .doSelec elect( t( "contac "contact.na t.name=\ me=\""+ ""+ name name + "\"" ) if ( isCo isCont ntac act t == RC _SUCCESS SUCCESS ) { prin print( t( "Suc "Succe cess ss. . foun found d " + name name + " in cont contac act t reco record rd:\ :\n" n" + contactList.get contactList.getXML() XML() ); return contactList; contactList; } else { print print( ( "Coul "Could d not find find conta contact. ct. " + RCtoS RCtoStr tring ing( ( isCon isContac tact t ) ); return return null; null; } } var contact contactName Name = "FALCON "FALCON, , JENNIFE JENNIFER"; R"; findCont findContact act( ( contact contactName Name ); conta contactN ctNam ame e = "NOT "NOT A, CONTA CONTACT CT"; "; findCont findContact act( ( contact contactName Name );
SCFile.join() This method returns as a string the elements of either a Service Manager SCFile array object or a JavaScript array.
50
method does not use the Service Manager global global return code values. values. Note: Note: This method 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")
function function findInc findInciden ident( t( id ) { prin print( t( "Sea "Searc rchi hing ng for for Inci Incide dent nt reco record rd: : " + id + "... "..." " ); var var inci inciden dentF tFile ile = new new SCFi SCFile( le( "prob "probsum summa mary" ry" ); var var rc = inci inciden dentF tFile ile.do .doSe Selec lect( t( "numb "number= er=\" \"" " + id + "\"" "\"" ); i f ( r c = = R C _SUCCESS SUCCESS ) { print( print( "Succes "Success. s. found found Incident Incident record:\ record:\n" n" + inciden incidentFil tFile.ge e.getTex tText() t() ); print print( ( "Disp "Displa layin ying g the conte contents nts of the the acti action on field field as an object object: : " + inciden incidentFil tFile.ac e.action tion ); print print( ( "Disp "Displa layin ying g the conte contents nts of the the acti action on field field with with join( join() ) method: method: " + inciden incidentFil tFile.ac e.action tion.jo .join() in() ); return incidentFile; incidentFile; } else { prin print( t( "Cou "Could ld not not find find Inci Incide dent nt reco record rd. . " + RCto RCtoSt Stri ring ng( ( rc ) ); return return null; null; } } var inciden incidentID tID = "IM1010 "IM1010"; "; findInci findInciden dent( t( inciden incidentID tID );
SCFile.JSDate(dataType SCFile.JSDate(dataType ) This method, which was deprecated as of version 6.1 with the introduction of the SCFile object, converts converts Service Manager date/time date/time data into JavaScript JavaScript date/time date/time objects. objects. The SCFile object now automatically converts Service Manager 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 ) dataType ) This method method does not have any return values. values. The following following argument argument is valid for this method:
51
dataType
String String
Specif Specifies ies the data data type type of a field field in a SCFil SCFilee object 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 SCFile object containing the number of milliseconds you want to convert. Converts Converts the open.time open.time field into an SCFile object. object. (By default default the open.time field data is in the Service Manager date/time data type.) Converts the SCFile object into a JavaScript date/time object.
This example example requires requires a valid incident record with a value in the open.time open.time field (for example, example, "IM1010") as sample data: function function findInc findInciden ident( t( id ) { prin print( t( "Sea "Searc rchi hing ng for for inci incide dent nt: : " + id + "... "..." " ); var var inci inciden dentF tFile ile = new new SCFi SCFile( le( "prob "probsum summa mary" ry" ); var var f = incid incident entFi File. le.doS doSel elect ect( ( "numb "number= er=\" \""+ "+ id + "\"" "\"" ); i f ( f = = R C _SUCCESS SUCCESS ) { prin print( t( "Suc "Succe cess ss. . foun found d " + id + " in inci incide dent nt reco record rd:\ :\n" n" + incidentFile.ge incidentFile.getText() tText() ); prin print( t( "The "The valu value e of the the open open.t .tim ime e fiel field d is: is: " + incidentFile.open _time time ); print print( ( "Conv "Conver ertin ting g open. open.tim time e to an SCFil SCFile e objec object.. t..." ." ); var dat = new SCFil SCFile( e( incid inciden entFi tFile le.op .open en _time time ); prin print( t( "The "The new new SCFi SCFile le obje object ct is: is: " + dat dat ); print print( ( "Conv "Conver ertin ting g the SCFil SCFile e obje object ct to a JSDat JSDate.. e..." ." ); var j = dat.J dat.JSDa SDate te(); (); prin print( t( "The "The conv conver erte ted d SCFi SCFile le obje object ct is: is: " + j ); return incidentFile; incidentFile; } else { prin print( t( "Cou "Could ld not not find find inci incide dent nt reco record rd. . " + RCto RCtoSt Stri ring ng( ( f ) ); return return null; null; } } var inciden incidentID tID = "IM1010 "IM1010"; "; findInci findInciden dent( t( inciden incidentID tID );
SCFile.length() This method returns the number of array elements in an array stored in a Service Manager SCFile object. object. You can use this method to return the length length of Service Service Manager array array fields, which are always always stored as SCFile objects. objects. To query a particular particular array field in a SCFile object, object, you can use the following format: SCFile_object .array_field_name .length() .length() Replace any periods in the name of array_field_name with array_field_name with underscores underscores.. For example, example, convert the Service Manager array field update.action to update_action when querying it from JavaScript.
52
The syntax for the method is array_field_name .length() .length() No arguments are passed. The method returns the number of array elements in an array stored in a Service Manager 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 Service Manager array data). Displays the size of the action field using the Service Manager length() method. Converts the SCFile object into a JavaScript array using the Service Manager toArray() method. Displays the size of the new JavaScript array using the core JavaScript length property.
function function findInc findInciden idents( ts( query query ) { print print( ( "Sear "Searchi ching ng for incid incident ent recor records ds start startin ing g with with " + quer query y + "..." "..." ); var var inci inciden dentF tFile ile = new new SCFi SCFile( le( "prob "probsum summa mary" ry" ); var findInc findInciden ident t = inciden incidentFil tFile.do e.doSel Select( ect( "number# "number#\""+ \""+ query query + "\"" "\"" ); if ( find findIn Inci cide dent nt == RC _SUCCESS SUCCESS ) { print print( ( "Succ "Succes ess. s. Found Found incid incident ent recor records ds start startin ing g with with " + query query + ". The The firs first t recor record d is:\n is:\n" " + incid incident entFi File le ); var objectSi objectSize ze = inciden incidentFil tFile.ge e.getSiz tSize(); e(); print print( ( "Runn "Runnin ing g the the getS getSize ize() () meth method od on the the retu returne rned d SCFil SCFile e objec object t produ produces ces the the follo followi wing ng resul result: t: " + objec objectSi tSize ze ); var actionTe actionText xt = inciden incidentFil tFile.ac e.action tion; ; print print( ( "The "The conte content nts s of the actio action n field field is:\n is:\n" " + actio actionT nText ext ); var actionSize actionSize = incidentFile.ac incidentFile.action.get tion.getSize(); Size(); prin print( t( "The "The size size of the the acti action on fiel field d is: is: " + acti action onSi Size ze ); print print( ( "Conv "Conver ertin ting g the SCFil SCFile e obje object ct to a JavaS JavaScri cript pt array array.." .." ); var incidentArray incidentArray = incidentFile.t incidentFile.toArray() oArray(); ; print print( ( "The "The new new JavaS JavaScr cript ipt array array is:\n is:\n" " + incid incident entAr Array ray ); var arraySiz arraySize e = inciden incidentArr tArray.l ay.leng ength; th; prin print( t( "The "The size size of the the conv conver erte ted d arra array y is: is: " + arra arrayS ySiz ize e ); return incidentFile; incidentFile; } else { print print( ( "Coul "Could d not find find incid incident ent recor records ds start startin ing g with with " + query query + ". " + RCto RCtoStr Strin ing( g( findI findInci ncide dent nt ) ); return return null; null; } } var inciden incidentQue tQuery ry = "IM1005" "IM1005"; ; findIncidents( findIncidents( incidentQuery incidentQuery );
53
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. method does not use the Service Manager global global return code values. values. Note: Note: This method 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")
function function findInc findInciden ident( t( id ) { prin print( t( "Sea "Searc rchi hing ng for for Inci Incide dent nt reco record rd: : " + id + "... "..." " ); var var inci inciden dentF tFile ile = new new SCFi SCFile( le( "prob "probsum summa mary" ry" ); var var rc = inci inciden dentF tFile ile.do .doSe Selec lect( t( "numb "number= er=\" \"" " + id + "\"" "\"" ) i f ( r c = = R C _SUCCESS SUCCESS ) { print( print( "Succes "Success. s. found found Incident Incident record:\ record:\n" n" + inciden incidentFil tFile.ge e.getTex tText() t() ); print print( ( "Conv "Conver ertin ting g the actio action n fiel field d to a JavaS JavaScr cript ipt array array... ..." " ); var a = incident incidentFil File.ac e.action tion.toA .toArra rray(); y(); prin print( t( "The "The acti action on fiel field d arra array y cont contai ains ns the the foll follow owin ing: g: " + a ); print print( ( "Push "Pushin ing g new new arra array y entry entry.. ..." ." ); var addOn addOne e = a.pus a.push( h( "Firs "First t array array item" item" ); prin print( t( "The "The numb number er of item items s in the the arra array y are: are: " + addO addOne ne ); prin print( t( "The "The acti action on fiel field d arra array y cont contai ains ns the the foll follow owin ing: g: " + a ); print print( ( "Popp "Poppin ing g new new arra array y entry entry.. ..." ." ); var remov removeOn eOne e = a.pop a.pop() (); ; prin print( t( "The "The arra array y item item remo remove ved d was: was: " + remo remove veOn One e ); prin print( t( "The "The acti action on fiel field d arra array y cont contai ains ns the the foll follow owin ing: g: " + a ); return incidentFile; incidentFile; } else { prin print( t( "Cou "Could ld not not find find Inci Incide dent nt reco record rd. . " + RCto RCtoSt Stri ring ng( ( rc ) ); return return null; null; } } var inciden incidentID tID = "IM1010 "IM1010"; "; findInci findInciden dent( t( inciden incidentID tID );
54
SCFile.push(arrayItem 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. array. If you apply this method to a Service Manager Manager array object, then it adds the item but does not return the number of entries in the array. method does not use the Service Manager global global return code values. values. Note: Note: This method The syntax is: push( arrayItem ) The following argument is valid for this method: arrayItem
String String
Specif Specifies ies the array array item item you you want want to add to a JavaSc JavaScrip riptt array. 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")
function function findInc findInciden ident( t( id ) { prin print( t( "Sea "Searc rchi hing ng for for Inci Incide dent nt reco record rd: : " + id + "... "..." " ); var var inci inciden dentF tFile ile = new new SCFi SCFile( le( "prob "probsum summa mary" ry" ); var var rc = inci inciden dentF tFile ile.do .doSe Selec lect( t( "numb "number= er=\" \"" " + id + "\"" "\"" ); i f ( r c = = R C _SUCCESS SUCCESS ) { print( print( "Succes "Success. s. found found Incident Incident record:\ record:\n" n" + inciden incidentFil tFile.ge e.getTex tText() t() ); print print( ( "Conv "Conver ertin ting g the actio action n fiel field d to a JavaS JavaScr cript ipt array array... ..." " ); var a = incident incidentFil File.ac e.action tion.toA .toArra rray(); y(); prin print( t( "The "The acti action on fiel field d arra array y cont contai ains ns the the foll follow owin ing: g: " + a ); print print( ( "Push "Pushin ing g new new arra array y entry entry.. ..." ." ); var addOn addOne e = a.pus a.push( h( "Firs "First t array array item" item" ); prin print( t( "The "The numb number er of item items s in the the arra array y are: are: " + addO addOne ne ); prin print( t( "The "The acti action on fiel field d arra array y cont contai ains ns the the foll follow owin ing: g: " + a ); print print( ( "Push "Pushin ing g new new arra array y entry entry.. ..." ." ); var addTw addTwo o = a.pus a.push( h( "Seco "Second nd array array item" item" ); prin print( t( "The "The numb number er of item items s in the the arra array y are: are: " + addT addTwo wo ); prin print( t( "The "The acti action on fiel field d arra array y cont contai ains ns the the foll follow owin ing: g: " + a ); return incidentFile; incidentFile; } else { prin print( t( "Cou "Could ld not not find find Inci Incide dent nt reco record rd. . " + RCto RCtoSt Stri ring ng( ( rc ) ); return return null; null; } } var inciden incidentID tID = "IM1010 "IM1010"; ";
55
findInci findInciden dent( t( inciden incidentID tID );
SCFile.setValue(newValue SCFile.setValue(newValue ) This method adds or updates a Service Manager record with a specified new field value. method does not use the Service Manager global global return codes and does not return return any Note: Note: This method value. The syntax is setValue( newValue ). newValue ). The following following argument argument is valid for this method: method: at newValue
String String
Specif Specifies ies the new value value for the Servic Servicee Manage Managerr object. object. Preced Precedee specia speciall charac character terss 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")
function function findInc findInciden ident( t( id, value value ) { prin print( t( "Sea "Searc rchi hing ng for for Inci Incide dent nt reco record rd: : " + id + "... "..." " ); var var inci inciden dentF tFile ile = new new SCFi SCFile( le( "prob "probsum summa mary" ry" ); var var rc = inci inciden dentF tFile ile.do .doSe Selec lect( t( "numb "number= er=\" \"" " + id + "\"" "\"" ); i f ( r c = = R C _SUCCESS SUCCESS ) { print print( ( "Succ "Succes ess. s. found found Incid Incident ent recor record d " + id ); print print( ( "Disp "Displa layin ying g the conte contents nts of the the acti action on field field as an object object: : " + inciden incidentFil tFile.a e.actio ction n ); print print( ( "Sett "Settin ing g the the valu value e of the actio action n field field.. ..." ." ); incidentFile.ac incidentFile.action.set tion.setValue( Value( value ); prin print( t( "Dis "Displ play ayin ing g the the cont conten ents ts of the the site site fiel field d as an obje object ct: : " + incidentFile.ac incidentFile.action tion ); print print( ( "Disp "Displa layin ying g the Incid Incident ent recor record: d: " + inci inciden dentF tFile ile ); return incidentFile; incidentFile; } else { prin print( t( "Cou "Could ld not not find find Inci Incide dent nt reco record rd. . " + RCto RCtoSt Stri ring ng( ( rc ) ); return return null; null; } } var inciden incidentID tID = "IM1010 "IM1010"; "; var newValu newValue e = "New descript description" ion"; ; findInci findInciden dent( t( inciden incidentID, tID, newValu newValue e );
SCFile.shift() This method removes the first element from a JavaScript array and returns the removed element as a string.
56
method does not use the Service Manager global global return code values. values. Note: Note: This method 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")
function function findInc findInciden ident( t( id ) { prin print( t( "Sea "Searc rchi hing ng for for Inci Incide dent nt reco record rd: : " + id + "... "..." " ); var var inci inciden dentF tFile ile = new new SCFi SCFile( le( "prob "probsum summa mary" ry" ); var var rc = inci inciden dentF tFile ile.do .doSe Selec lect( t( "numb "number= er=\" \"" " + id + "\"" "\"" ); i f ( r c = = R C _SUCCESS SUCCESS ) { print( print( "Succes "Success. s. found found Incident Incident record:\ record:\n" n" + inciden incidentFil tFile.ge e.getTex tText() t() ); print print( ( "Conv "Conver ertin ting g the actio action n fiel field d to a JavaS JavaScr cript ipt array array... ..." " ); var a = incident incidentFil File.ac e.action tion.toA .toArra rray(); y(); prin print( t( "The "The acti action on fiel field d arra array y cont contai ains ns the the foll follow owin ing: g: " + a ); print print( ( "Push "Pushin ing g new new arra array y entry entry.. ..." ." ); var addOn addOne e = a.pus a.push( h( "Firs "First t array array item" item" ); prin print( t( "The "The numb number er of item items s in the the arra array y are: are: " + addO addOne ne ); prin print( t( "The "The acti action on fiel field d arra array y cont contai ains ns the the foll follow owin ing: g: " + a ); print print( ( "Shif "Shifti ting ng array array one entry entry.. ..." ." ); var removeOn removeOne e = a.shift a.shift(); (); prin print( t( "The "The arra array y item item remo remove ved d was: was: " + remo remove veOn One e ); prin print( t( "The "The acti action on fiel field d arra array y cont contai ains ns the the foll follow owin ing: g: " + a ); return incidentFile; incidentFile; } else { prin print( t( "Cou "Could ld not not find find Inci Incide dent nt reco record rd. . " + RCto RCtoSt Stri ring ng( ( rc ) ); return return null; null; } } var inciden incidentID tID = "IM1010 "IM1010"; "; findInci findInciden dent( t( inciden incidentID tID );
SCFile.toArray() This method converts a Service Manager Datum object into a JavaScript array.
57
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")
function function findInc findInciden ident( t( id ) { prin print( t( "Sea "Searc rchi hing ng for for Inci Incide dent nt reco record rd: : " + id + "... "..." " ); var var inci inciden dentF tFile ile = new new SCFi SCFile( le( "prob "probsum summa mary" ry" ); var var rc = inci inciden dentF tFile ile.do .doSe Selec lect( t( "numb "number= er=\" \"" " + id + "\"" "\"" ); i f ( r c = = R C _SUCCESS SUCCESS ) { print( print( "Succes "Success. s. found found Incident Incident record:\ record:\n" n" + inciden incidentFil tFile.ge e.getTex tText() t() ); print print( ( "Conv "Conver ertin ting g the actio action n fiel field d to a JavaS JavaScr cript ipt array array... ..." " ); var a = incident incidentFil File.ac e.action tion.toA .toArra rray(); y(); prin print( t( "The "The acti action on fiel field d cont contai ains ns the the foll follow owin ing g " + a ); return incidentFile; incidentFile; } else { prin print( t( "Cou "Could ld not not find find Inci Incide dent nt reco record rd. . " + RCto RCtoSt Stri ring ng( ( rc ) ); return return null; null; } } var inciden incidentID tID = "IM1010 "IM1010"; "; findInci findInciden dent( t( inciden incidentID tID );
SCFile.unshift(arrayItem SCFile.unshift(arrayItem ) This method adds an entry to the beginning of a JavaScript array and returns the total number of entries entries in the array. If you apply this method method to a Service Manager Manager array object, object, then it adds the item but does not return the number of entries in the array. method does not use the Service Manager global global return code values. values. Note: Note: This method The syntax for this method is unshift( arrayItem ) The following argument is valid for this method: Argu Argume ment nt
Data Data type type
Desc Descrip riptio tion n
58
arrayItem
String String
Specifi Specifies es the the array array item item you want want to add to a JavaSc JavaScrip riptt array. 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")
function function findInc findInciden ident( t( id ) { prin print( t( "Sea "Searc rchi hing ng for for Inci Incide dent nt reco record rd: : " + id + "... "..." " ); var var inci inciden dentF tFile ile = new new SCFi SCFile( le( "prob "probsum summa mary" ry" ); var var rc = inci inciden dentF tFile ile.do .doSe Selec lect( t( "numb "number= er=\" \"" " + id + "\"" "\"" ) i f ( r c = = R C _SUCCESS SUCCESS ) { print( print( "Succes "Success. s. found found Incident Incident record:\ record:\n" n" + inciden incidentFil tFile.ge e.getTex tText() t() ); print print( ( "Conv "Conver ertin ting g the actio action n fiel field d to a JavaS JavaScr cript ipt array array... ..." " ); var a = incident incidentFil File.ac e.action tion.toA .toArra rray(); y(); prin print( t( "The "The acti action on fiel field d arra array y cont contai ains ns the the foll follow owin ing: g: " + a ); print( print( "Unshif "Unshifting ting array array one entry... entry..." " ); var unshi unshifti fting ng = a.uns a.unshi hift( ft( "Firs "First t array array item" item" ); prin print( t( "The "The numb number er of item items s in the the arra array y are: are: " + unsh unshif ifti ting ng ); prin print( t( "The "The acti action on fiel field d arra array y cont contai ains ns the the foll follow owin ing: g: " + a ); return incidentFile; incidentFile; } else { prin print( t( "Cou "Could ld not not find find Inci Incide dent nt reco record rd. . " + RCto RCtoSt Stri ring ng( ( rc ) ); return return null; null; } } var inciden incidentID tID = "IM1010 "IM1010"; "; findInci findInciden dent( t( inciden incidentID tID );
JavaScript methods for the XML object XML.addAttribute(AttributeName XML.addAttribute(AttributeName , AttributeValue ) This method method inserts an attribute attribute and an attribute value value into the current element. It returns an XML object containing containing the updated updated element; or returns null if the method cannot add the attribute. attribute. Use the XMLgetxxx XMLgetxxx methods methods to navigate through an XML document. The syntax is: addAttribute( AttributeName , AttributeValue ) AttributeValue ) The following arguments are valid for this method:
59
at AttributeName
String String
Specif Specifies ies the text text stri string ng you you want want the script script to use use as as the the XML attribu attribute te name. name. Must Must cont contain ain characters valid for an XML element (for example, the string cannot include the characters < or >).
AttributeValue
String String
Specif Specifies ies the text text stri string ng you you want want the script script to use use as as the the XML attribu attribute te value. value. Must Must cont contain ain characters valid for an XML element (for example, the string cannot include the characters < or >).
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 following sample data:
C:\test02.xml
containing the
"value1< "value1 parent2>" " /* * * * *
Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. The The scri script pt assi assign gns s valu values es to thes these e vari variab able les s late later r on: on: Use Use XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . Use Use sour source ceXM XMLS LStr trin ing g to stor store e a vali valid d XML XML stri string ng. . The The scri script pt sets sets the the cont conten ent t of XMLS XMLStr trin ing g to sour source ceXM XMLS LStr trin ing. g. */
var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test02. t02.xml xml", ", true ); /* * * * * *
Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t conta contain ining ing the the eleme element nt. . This This func functi tion on assu assume mes s that that ther there e is only only one one inst instan ance ce of the the targ target et elem elemen ent t in the the sour source ce data data. . If it find finds s more more than than one one elem elemen ent t in the the data data it only only retu return rns s the the firs first t inst instan ance ce of the the elem elemen ent. t. */
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; } } return return node; node; }
60
/* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function createNewAttrib createNewAttribute( ute( searchResult, searchResult, targetNode, targetNode, attrName, attrName, attrValu attrValue e ) { prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + targ target etNo Node de ); if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); prin print( t( "Add "Addin ing g new new attr attrib ibut ute e " + attr attrNa Name me + " to elem elemen ent t " + elementN elementName ame ); searchResult.ad searchResult.addAttribu dAttribute( te( attrName, attrName, attrValue attrValue ); print print( ( "The "The new new objec object t is:\n is:\n" " + searc searchRe hResu sult lt ); return searchResult; searchResult; } else { prin print( t( "Can "Canno not t find find " + targ target et ); return return null; null; } } /* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Target TargetNod Node. e. Run Run func functio tions ns. .
*/
print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); var TargetN TargetNode ode = "parent "parent1"; 1"; var XMLSo XMLSour urce ce = XMLFi XMLFile; le; var searchR searchResul esults ts = findTarg findTargetEl etEleme ement( nt( XMLSourc XMLSource, e, TargetN TargetNode ode ); var Attribu AttributeNa teName me = "id"; "id"; var Attribu AttributeVa teValue lue = "test"; "test"; createNewAttrib createNewAttribute( ute( searchResults, searchResults, TargetNode, TargetNode, AttributeName, AttributeName, AttributeValue AttributeValue );
XML.addElement(String XML.addElement(String ) This method method inserts an XML element as a child of the current current element. It returns an XML object containing containing the new XML element; or returns null if the method cannot cannot add the element. Use the XML.getxxx XML.getxxx methods methods to navigate through an XML document. The syntax for this method is: addElement( String ) The following argument is valid: String
String String
Specif Specifies ies the text text stri string ng you you want want the script script to use as the XML eleme element nt name. name. Must Must cont contain ain characters valid for an XML element (for example, the string cannot include the characters < or >).
Example This example 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: "value1< "value1 parent2>" " /* Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s.
61
* * * *
Use Use Use Use The The The The
XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . sour source ceXM XMLS LStr trin ing g to stor store e a vali valid d XML XML stri string ng. . scri script pt sets sets the the conte content nt of XMLStr XMLString ing to sourc sourceX eXMLS MLStr tring ing. . scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */
var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test02. t02.xml xml", ", true ); var XMLSour XMLSource; ce; var TargetNode; TargetNode; var searchResults; searchResults; var printResults; printResults; var NewNodeName; NewNodeName; /* * * * * *
Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t cont contai aini ning ng the elem elemen ent. t. This This funct functio ion n assu assume mes s that that there there is only only one one inst instan ance ce of the the targ target et eleme element nt in the the sour source ce data data. . If it finds finds more more than than one one elem elemen ent t in the the data data it only only retu return rns s the the firs first t inst instan ance ce of the the elem elemen ent. t. */
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; } } return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function function createN createNewNo ewNode( de( searchRe searchResul sult, t, targetN targetNode, ode, nodeName nodeName ) { prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + targ target etNo Node de ); if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); prin print( t( "Add "Addin ing g new new node node " + node nodeNa Name me + " to elem elemen ent t " + elem elemen entN tNam ame e ); var newNode newNode = searchRe searchResult sult.ad .addEle dElement ment( ( nodeNam nodeName e ); print print( ( "The "The new new objec object t is:\n is:\n" " + searc searchRe hResu sult lt );
62
return searchResult; searchResult; } else { prin print( t( "Can "Canno not t find find " + targ target et ); return return null; null; } } /* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Target TargetNod Node. e. Run Run func functio tions ns. .
*/
print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "parent "parent1"; 1"; XMLSourc XMLSource e = XMLFile XMLFile; ; searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); NewNodeN NewNodeName ame = "child8 "child8"; "; createNewNode( createNewNode( searchResults, TargetNode, NewNodeName NewNodeName );
XML.appendNode(name XML.appendNode(name ) This method method inserts an XML node into an XML object. It returns an XML object containing containing the new XML node; or returns null if the method cannot cannot append the node to the current target node. 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 ) name ) The following argument is valid for this method: at name
String String
Specif Specifies ies the XML node node name name you you want want to to append append to the target target XML object object.. Mus Mustt contain characters valid for XML (for example, the string cannot include the characters < or > except as XML entities such as < and >).
Example This example example appends appends an XML node to an XML source object. It requires requires an XML object object containing containing sample data such as: "" function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else
63
{ node node = childN childNod ode; e; } } return return node; node; } function function appendN appendNewNo ewNode( de( type, type, name, name, value, value, xmlSourc xmlSource, e, target target ) { print print( ( "The "The XML sourc source e obje object ct is: is: " + xmlSo xmlSour urce) ce); ; prin print( t( "Cre "Creat atin ing g node node of type type: : " + type type + " name named: d: " + name name + " with with valu value: e: " + valu value e ); var var NewN NewNode ode = xmlS xmlSour ource. ce.cr creat eateN eNode ode( ( type, type, name, name, value value ); print print( ( "Appe "Appendi nding ng " + NewNo NewNode. de.to toXML XMLSt Strin ring( g() ) + " to: to: " + targe target t ); var FoundNo FoundNode de = findTarg findTargetE etEleme lement( nt( xmlSour xmlSource, ce, target target ); var appende appendedNod dNode e = FoundNo FoundNode.a de.appen ppendNo dNode( de( NewNode NewNode ); prin print( t( "The "The new new XML XML obje object ct is: " + xmlS xmlSou ourc rce e ); } var XMLOb XMLObje ject ct = new XML() XML(); ; XMLObjec XMLObject t = XMLObje XMLObject.s ct.setCo etConte ntent( nt( " nt> ent>" " ); var NewNo NewNode deTyp Type e = 1; var NewNode NewNodeName Name = "node"; "node"; var NewNode NewNodeValu Value e = "test"; "test"; var TargetN TargetNode ode = "docume "document"; nt"; appendNewNode( appendNewNode( NewNodeType, NewNodeType, NewNodeName, NewNodeName, NewNodeValue, NewNodeValue, XMLObject, XMLObject, TargetNo TargetNode de );
XML.createNode(type XML.createNode(type , name , value ) This method method creates an XML node from an XML object. object. It returns an XML object containing containing the new XML node; or returns null if the method cannot cannot create the node. This method method requires an existing existing XML object with a document element, but does not update the object. The syntax is: createNode( type , name , value ) value ) The following arguments are valid for this method:
type
Integer Integer
Specif Specifies ies the XML DOM node node type type for the node node you you want want the the scri script pt to create create.. This This meth method od accepts only only XML DOM types types 1, 2, and 3. See the W3C Web Web site for a complete complete listing listing of XML DOM node-types by integer.
name
String String
Specif Specifies ies the text text stri string ng you you want want the the script script to add as the XML node node name. name. Must Must cont contain ain characters valid for XML (for example, the string cannot include the characters < or > except as XML entities such as < and >).
value
String String
Specif Specifies ies the text text stri string ng you you want want the the script script to add as the XML node node value. value. Must Must cont contain ain characters valid for XML (for example, the string cannot include the characters < or > except as XML entities such as < and >).
Example This example example creates an XML node from an XML source object. It requires requires as sample data an XML object, such as an object containing: containing: "" " var var var var
XMLObjec XMLObject t = XMLObje XMLObject.s ct.setCo etConte ntent( nt( " nt> ent>" " ); function function createN createNewNo ewNode( de( type, type, name, name, value, value, xmlSourc xmlSource e ) { print print( ( "The "The XML sourc source e obje object ct is: is: " + xmlSo xmlSour urce) ce); ; prin print( t( "Cre "Creat atin ing g node node of type type: : " + type type + " name named: d: " + name name + " with with valu value: e: " + valu value e ); var var NewN NewNode ode = xmlS xmlSour ource. ce.cr creat eateN eNode ode( ( type, type, name, name, value value ); print print( ( "The "The XML sourc source e obje object ct remai remains ns uncha unchang nged: ed: " + XMLOb XMLObje ject ct ); prin print( t( "The "The new new node node conv conver erte ted d to an XML XML stri string ng is: is: " + NewNode.toXMLSt NewNode.toXMLString() ring() ); print print( ( "Appl "Applyin ying g the getNa getName me metho method d to the the new new node node prod produce uces: s: " + NewNode.getName NewNode.getName() () ); print print( ( "Appl "Applyin ying g the getVa getValue lue metho method d on the new new node node produ produce ces: s: " + NewNode.getValu NewNode.getValue() e() ); } NewNo NewNodeT deTyp ype e = 1; NewNodeN NewNodeName ame = "node"; "node"; NewNodeV NewNodeValu alue e = "test"; "test"; createNewNode( createNewNode( NewNodeType, NewNodeName, NewNodeName, NewNodeValue, NewNodeValue, XMLObject XMLObject ); NewNo NewNodeT deTyp ype e = 2; NewNodeN NewNodeName ame = "id"; "id"; NewNodeV NewNodeValu alue e = "test"; "test"; createNewNode( createNewNode( NewNodeType, NewNodeName, NewNodeName, NewNodeValue, NewNodeValue, XMLObject XMLObject ); NewNo NewNodeT deTyp ype e = 3; NewNodeN NewNodeName ame = null; null; NewNodeV NewNodeValu alue e = "Text "Text node"; node"; createNewNode( createNewNode( NewNodeType, NewNodeName, NewNodeName, NewNodeValue, NewNodeValue, XMLObject XMLObject );
XML.getAttributeNode(Attribute XML.getAttributeNode( Attribute ) This method returns an XML object containing the target attribute the current element; or returns null if the method cannot cannot find the target attribute attribute in the current current element. Use the other XML.get XML.getxxx xxx methods methods to navigate through an XML document. The syntax is: getAttributeNode( Attribute ) Attribute ) The following argument is valid for this method:
Attribute
String String
Specif Specifies ies the XML attribu attribute te you you want want the script script to return return..
Example This example example searches for a particular particular attribute attribute of any given element element in an XML document. It requires a local XML file, such as a file called C:\test.xml containing the following sample data: " />" /* * * * * *
Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t cont contai aini ning ng the elem elemen ent. t. This This funct functio ion n assu assume mes s that that there there is only only one one inst instan ance ce of the targ target et elem elemen ent t in the the sour source ce data data. . If it find finds s more more than than one one elem elemen ent t in the data, data, it only only retur returns ns the firs first t inst instan ance ce of the the elem elemen ent. t. */
65
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; } } return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function function printFi printFindRe ndResult sults( s( target, target, searchRe searchResult sult, , attribut attribute e ) { prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + targ target et ); if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); var attribut attributeFou eFound nd = findAtt findAttribu ributeNo teNode( de( searchR searchResul esult, t, attribu attribute te ); return attributeFound; attributeFound; } else { prin print( t( "Can "Canno not t find find " + targ target et ); return return null; null; } } /* Crea Create te a func functi tion on to find find the the attr attrib ibut ute e node node of the the targ target et elem elemen ent t */ function findAttributeNode( findAttributeNode( sourceObject, sourceObject, attribute attribute ) { print print( ( "Look "Looking ing for for attri attribu bute te node node " + attri attribu bute te ); var attribu attributeNo teNode de = sourceO sourceObjec bject.ge t.getAtt tAttrib ributeN uteNode( ode( attribut attribute e ); if ( attr attrib ibut uteN eNod ode e != null null ) { print print( ( "Succ "Succes ess. s. Found Found attri attribut bute e " + attri attribut buteN eNode ode ); return attributeNode; attributeNode; } else { print print( ( "Fail "Failur ure. e. Did Did not not find find attr attribu ibute te " + attr attribu ibute te );
66
return return null; null; } } /* Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. * Use Use XMLF XMLFil ile e to store store a vali valid d XML XML file file.* .*/ / var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test.xm t.xml", l", true true ); var TargetN TargetNode ode = "child1 "child1"; "; var XMLSo XMLSour urce ce = XMLFi XMLFile; le; var TargetA TargetAttri ttribute bute = "attrib "attribute1 ute1"; "; /* Run Run funct functio ions ns
*/
print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( TargetNode, TargetNode, searchResults, searchResults, TargetAttribute TargetAttribute );
XML.getAttributeValue(Attribute XML.getAttributeValue( Attribute ) This method returns the string value of the target attribute; or returns null if the method cannot find an attribute attribute value. value. Use the other XML.get XML.getxxx xxx methods methods to navigate through an XML document. The syntax is: getAttributeValue( Attribute ) Attribute ) The following argument is valid for this method: at Attribute
String String
Specif Specifies ies the XML attribu attribute te whose whose value value you want want the metho method d to return return..
Example This example example searches searches for the attribute attribute value of any given element in an XML document. document. It requires as sample data a local XML file, such as a file called C:\test.xml containing: " />" /* Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. * Use Use XMLF XMLFil ile e to stor store e a vali valid d XML XML file file. . * The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */ var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test.xm t.xml", l", true true ); var XMLSour XMLSource; ce; var TargetNode; TargetNode; var TargetAttribute TargetAttribute; ; var searchResults; searchResults; /* * * * * *
Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t cont contai aini ning ng the elem elemen ent. t. This This funct functio ion n assu assume mes s that that there there is only only one one inst instan ance ce of the the targ target et eleme element nt in the the sour source ce data data. . If it find finds s more more than than one one elem elemen ent t in the data data it only only retu return rns s the the firs first t inst instan ance ce of the the elem elemen ent. t. */
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) {
67
while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; } } return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function function printFi printFindRe ndResult sults( s( target, target, searchRe searchResult sult, , attribut attribute e ) { prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + targ target et ); if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); var attribut attributeFou eFound nd = findAtt findAttribu ributeVa teValue( lue( searchR searchResul esult, t, attribu attribute te ); return attributeFound; attributeFound; } else { prin print( t( "Can "Canno not t find find " + targ target et ); return return null; null; } } /* Crea Create te a func functi tion on to find find the the attr attrib ibut ute e node node of the the targ target et elem elemen ent t */ function function findAtt findAttribu ributeVa teValue( lue( sourceOb sourceObjec ject, t, attribu attribute te ) { print print( ( "Look "Looking ing for for attri attribu bute te value value of " + attri attribu bute te ); var attribu attributeVa teValue lue = sourceOb sourceObjec ject.ge t.getAtt tAttribu ributeVa teValue lue( ( attribu attribute te ); if ( attr attrib ibut uteV eVal alue ue != null null ) { prin print( t( "Suc "Succe cess ss. . The The valu value e of " + attr attrib ibut ute e + " is " + attributeValue attributeValue ); return attributeValue; attributeValue; } else { prin print( t( "Fai "Fail. l. Did Did not not find find attr attrib ibut ute e " + attr attrib ibut ute e ); return return null; null; } }
68
/* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Targe TargetNo tNode de. . Run Run func functio tions ns print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "child1 "child1"; "; XMLSourc XMLSource e = XMLFile XMLFile; ; TargetAttribute TargetAttribute = "attribute1"; "attribute1"; searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( TargetNode, TargetNode, searchResults, searchResults, TargetAttribute TargetAttribute );
*/
XML.getDocumentElement() This method method searches an XML object for the DOM document element element (or "root" node). node). If successful, successful, it returns returns an XML object containing containing the document element element and all of its child elements. 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 example displays the XML document element element from four different input sources. 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:
"" />" A non-compliant XML string, such as:
"" >" An empty XML object
/* * * * * * * * *
Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. Use Use good goodXM XML L to store store a vali valid d XML XML stri string ng. . Use Use badX badXML ML to stor store e any any erro errone neou ous s XML XML stri string ng, , in this this case case a seco second nd d doc ocum umen ent t * elem elemen ent. t. Use Use xmlO xmlObj bjec ect t to store store a vali valid d XML XML obje object ct such such as the syste system. m.use users rs lis list. t. The The scri script pt sets sets the the cont conten ent t of xmlS xmlStr trin ing g to good goodXM XML; L; the the cont conten ent t of xmlBa xmlBad d to badXM badXML; L; and and the the cont conten ent t of xmlE xmlEmp mpty ty to an XML obje object ct*/ */
var goodXML = ""; />"; var badXML = "< />"; var xmlObje xmlObject ct = system.u system.users sers; ; var xmlSt xmlStri ring ng = new XML() XML(); ; xmlStrin xmlString g = xmlStri xmlString.s ng.setCo etConte ntent( nt( goodXML goodXML ); var var xmlB xmlBad ad = new new XML( XML(); ); xmlBad xmlBad = xmlBad. xmlBad.setC setConte ontent( nt( badXML badXML ); prin print( t( "The "The valu value e of xmlB xmlBad ad is:\ is:\n" n" + xmlB xmlBad ad ); var xmlEm xmlEmpt pty y = new XML() XML(); ;
69
/* Creat Create e a func functio tion n to execu execute te the the getD getDocu ocume mentE ntElem lemen ent t meth method od on the the document document argumen argument. t. */ function function getDocE getDocElem( lem( document document ) { var DocElem = document.getDoc document.getDocumentEl umentElement(); ement(); if ( DocE DocEle lem m != null null ) { var DocElemN DocElemName ame = DocElem. DocElem.get getNode NodeName Name(); (); print print( ( "Succ "Succes ess. s. Found Found the docum documen ent t eleme element nt " + the follo followin wing g objec object: t: \n" \n" + docum document ent ); return DocElem; DocElem; } else { print print( ( "Erro "Error. r. Did Did not find find docum document ent eleme element nt in objec object: t: \n" \n" + docum document ent ); return return null; null; } } /* Run Run the the getDo getDocEl cElem em and and getD getDocE ocEle lemNa mName me func functio tions ns on * inpu input t sour source ces. s. Prin Print t the the obje object cts s retu return rned ed by each each print print( ( "Now "Now sear searchi ching ng for for ); getDocEl getDocElem( em( xmlObje xmlObject ct ); print print( ( "Now "Now sear searchi ching ng for for ); getDocEl getDocElem( em( xmlStri xmlString ng ); print print( ( "Now "Now sear searchi ching ng for for string...\n" string...\n" ); getDocEl getDocElem( em( xmlBad xmlBad ); print print( ( "Now "Now sear searchi ching ng for for ); getDocEl getDocElem( em( xmlEmpt xmlEmpty y );
DocEl DocElemN emNam ame e + " in
the follo followin wing g
four four funct functio ion. n. */
a docum documen ent t eleme element nt in a vali valid d XML XML obje object. ct... ..\n" \n"
a docum documen ent t eleme element nt in a vali valid d XML XML stri string. ng... ..\n" \n"
a docum documen ent t eleme element nt in a nonnon-com compl plian iant t XML
a docum documen ent t eleme element nt in an empty empty XML XML objec object. t...\ ..\n" n"
XML.getFirstAttribute(Element 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. The syntax is getFirstAttribute(); or getFirstAttribute(Element getFirstAttribute( Element ). ). The following following argumen argumentt is valid for this method: at Element
String String
Contai Contains ns the name name of the elemen elementt you you want want the the method method to use use as as the the starti starting ng positi position on when searching for the first attribute.
Example This example example displays displays the first attribute attribute of any element element you select. It allows you to select an element element from two different input sources. sources. It requires the following following sample data: data:
A local XML file, such as a file called
" />" A valid XML string, such as:
C:\test.xml
containing the following sample data:
70
"" /* * * * *
Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. Use Use XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . Use Use sour source ceXM XMLS LStr trin ing g to stor store e a vali valid d XML XML stri string ng. . The The scri script pt sets sets the the conte content nt of XMLStr XMLString ing to sourc sourceX eXMLS MLStr tring ing. . The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */
var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test.xm t.xml", l", true true ); var sourceXMLString sourceXMLString = ""; />"; var XMLSt XMLStri ring ng = new XML() XML(); ; XMLStrin XMLString g = XMLStri XMLString.s ng.setCo etConte ntent( nt( sourceXM sourceXMLSt LString ring ); var XMLSour XMLSource; ce; var TargetNode; TargetNode; var searchResults; searchResults; var attributeResult attributeResults; s; /* Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a * parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t * conta contain ining ing the the eleme element nt. . * * *
This This func functi tion on assu assume mes s that that ther there e is only only one one inst instan ance ce of the the targ target et elem elemen ent t in the the sour source ce data data. . If it find finds s more more than than one one elem elemen ent t in the the data data it only only retu return rns s the the firs first t inst instan ance ce of the the elem elemen ent. t. */
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; } } return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function function printFi printFindRe ndResult sults( s( target, target, searchRe searchResult sult ) { if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt +
71
"\n" "\n" ); return searchResult; searchResult; } else { prin print( t( "Can "Canno not t find find " + targ target et ); return return null; null; } } /* Crea Create te a func functi tion on to find find the the firs first t attr attrib ibut ute e of the the targ target et elem elemen ent t */ function findFirstAttribute( findFirstAttribute( sourceObject, targetNode ) { var startin startingNod gNode e = findTar findTargetE getEleme lement( nt( sourceO sourceObjec bject, t, targetN targetNode ode ) var attribute attribute = startingNode.ge startingNode.getFirstAt tFirstAttribute tribute(); (); if ( attr attrib ibut ute e != null null ) { return attribute; attribute; } else { return return null; null; } } /* Crea Create te func functi tion on to prin print t the the 1st 1st attr attrib ibut ute e of the the targ target et elem elemen ent t */ function printAttributeResult printAttributeResults( s( target, searchResult ) { if ( sear search chRe Resu sult lt != null null ) { var attributeName attributeName = searchResult.g searchResult.getNodeNa etNodeName(); me(); prin print( t( "The "The firs first t attr attrib ibut ute e of " + targ target et + " is: is: " + attr attrib ibut uteN eNam ame e ); } else { prin print( t( "The "There re are are no attr attrib ibut utes es of " + targ target et ); } } /* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Targe TargetNo tNode de. . Run Run func functio tions ns */ print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "child1 "child1"; "; XMLSourc XMLSource e = XMLFile XMLFile; ; prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + Targ Target etNo Node de ); searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( TargetNode, TargetNode, searchResults searchResults ); attribut attributeRe eResult sults s = findFirs findFirstAt tAttrib tribute( ute( XMLSourc XMLSource, e, TargetNo TargetNode de ); printAttributeR printAttributeResults( esults( TargetNode, TargetNode, attributeResult attributeResults s ); /* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Targe TargetNo tNode de. . Run Run func functio tions ns */ print print( ( "Pro "Proces cessi sing ng XML XML from from XMLSt XMLStri ring. ng... .. \n" \n" ); TargetNo TargetNode de = "child2 "child2"; "; XMLSourc XMLSource e = XMLStri XMLString; ng; prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + Targ Target etNo Node de ); searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( TargetNode, TargetNode, searchResults searchResults ); attribut attributeRe eResult sults s = findFirs findFirstAt tAttrib tribute( ute( XMLSourc XMLSource, e, TargetNo TargetNode de ); printAttributeR printAttributeResults( esults( TargetNode, TargetNode, attributeResult attributeResults s );
72
XML.getFirstChildElement(Element 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 getFirstChildElement(Element ). ). The following argument is valid for this method:
Element
String String
Contai Contains ns the the name name of of the the elem element ent you you want want the metho method d to use use as the starti starting ng positi position on when when searching for the first child element.
Example This example example displays displays the first child element of any element you select. select. It allows you to select an element element from two different input input sources. It requires the following following sample data:
A local XML file, such as a file called
" />" A valid XML string, such as:
C:\test.xml
containing the following sample data:
"" /* * * * *
Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. Use Use XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . Use Use sour source ceXM XMLS LStr trin ing g to stor store e a vali valid d XML XML stri string ng. . The The scri script pt sets sets the the conte content nt of XMLStr XMLString ing to sourc sourceX eXMLS MLStr tring ing. . The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */
var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test.xm t.xml", l", true true ); var sourceXMLString sourceXMLString = ""; />"; var XMLSt XMLStri ring ng = new XML() XML(); ; XMLStrin XMLString g = XMLStri XMLString.s ng.setCo etConte ntent( nt( sourceXM sourceXMLSt LString ring ); var XMLSour XMLSource; ce; var TargetNode; TargetNode; var searchResults; searchResults; var childResults; childResults; /* * * * * * *
Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t conta contain ining ing the the eleme element nt. . This This func functi tion on assu assume mes s that that ther there e is only only one one inst instan ance ce of the the targ target et elem elemen ent t in the the sour source ce data data. . If it find finds s more more than than one one elem elemen ent t in the the data data, , it retur returns ns only only the firs first t inst instan ance ce of the the elem elemen ent. t. */
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) {
73
while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; } } return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function function printFi printFindRe ndResult sults( s( target, target, searchRe searchResult sult ) { if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); return searchResult; searchResult; } else { prin print( t( "Can "Canno not t find find " + targ target et ); return return null; null; } } /* Crea Create te a func functi tion on to find find the the firs first t chil child d elem elemen ent t of the the targ target et * elemen ment */ */ function function findFir findFirstCh stChild( ild( sourceOb sourceObject ject, , targetNo targetNode de ) { var startin startingNod gNode e = findTar findTargetE getEleme lement( nt( sourceO sourceObjec bject, t, targetN targetNode ode ); var firstChild firstChild = startingNode.ge startingNode.getFirstCh tFirstChildEleme ildElement(); nt(); if ( firs firstC tChi hild ld != null null ) { return firstChild; firstChild; } else { return return null; null; } } /* Crea Create te a func functi tion on to prin print t the the firs first t chil child d elem elemen ent t of the the * targ target et elem elemen ent. t.*/ */
74
function function printCh printChildR ildResul esults( ts( target, target, searchR searchResul esult t ) { if ( sear search chRe Resu sult lt != null null ) { var childName childName = searchResult.ge searchResult.getNodeNa tNodeName(); me(); prin print( t( "The "The firs first t chil child d elem elemen ent t of " + targ target et + " is: is: " + chil childN dNam ame e ); } else { prin print( t( "The "There re are are no chil child d elem elemen ents ts of " + targ target et ); } } /* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Targe TargetNo tNode de. . Run Run func functio tions ns */ print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "parent "parent1"; 1"; XMLSourc XMLSource e = XMLFile XMLFile; ; prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + Targ Target etNo Node de ); searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( TargetNode, TargetNode, searchResults searchResults ); childRes childResult ults s = findFirs findFirstChi tChild( ld( XMLSour XMLSource, ce, TargetN TargetNode ode ); printChildResul printChildResults( ts( TargetNode, TargetNode, childResults childResults ); /* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Targe TargetNo tNode de. . Run Run func functio tions ns
*/
print print( ( "Pro "Proces cessi sing ng XML XML from from XMLSt XMLStri ring. ng... .. \n" \n" ); TargetNo TargetNode de = "parent "parent2"; 2"; XMLSourc XMLSource e = XMLStri XMLString; ng; prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + Targ Target etNo Node de ); searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( TargetNode, TargetNode, searchResults searchResults ); childRes childResult ults s = findFirs findFirstChi tChild( ld( XMLSour XMLSource, ce, TargetN TargetNode ode ); printChildResul printChildResults( ts( TargetNode, TargetNode, childResults childResults );
XML.getName() The method, which is a synonym for getNodeName(), returns a string representing the name of the current current element or attribute; attribute; or returns null if the current node has no name. Use the other XML.get XML.getxxx xxx methods to navigate through an XML document. The syntax is: getName() No arguments are passed. Example This example example displays displays the names of the elements elements and attributes attributes in an XML document. document. It requires requires the following sample data:
A local XML file, such as a file called
" />" A valid XML string, such as:
C:\test.xml
containing the following sample data:
"0123 "0123" document>"
75
/* * * * *
Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. Use Use XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . Use Use sour source ceXM XMLS LStr trin ing g to stor store e a vali valid d XML XML stri string ng. . The The scri script pt sets sets the the conte content nt of XMLStr XMLString ing to sourc sourceX eXMLS MLStr tring ing. . The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */
var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test.xm t.xml", l", true true ); var sourceX sourceXMLSt MLString ring = "0123"; var XMLSt XMLStri ring ng = new XML() XML(); ; XMLStrin XMLString g = XMLStri XMLString.s ng.setCo etConte ntent( nt( sourceXM sourceXMLSt LString ring ); var XMLSour XMLSource; ce; funct function ion walkX walkXML ML( ( elem elem ) { print print( ( "Elem "Element ent " + elem. elem.ge getNa tName me() () ); var node node = elem.ge elem.getFir tFirstAt stAttrib tribute( ute(); ); whil while( e( node node != null null ) { var attrN attrName ame = node. node.ge getNa tName me(); (); var attrValu attrValue e = node.ge node.getNod tNodeVal eValue( ue(); ); prin print( t( "Att "Attri ribu bute te " + attr attrNa Name me + " = " + attr attrVa Valu lue e ); node = elem.getNextAtt elem.getNextAttribute( ribute(); ); } var nodeVal nodeValue ue = elem.get elem.getNod NodeVal eValue() ue(); ; if ( type typeof of node nodeVa Valu lue e == "str "strin ing" g" && node nodeVa Valu lue. e.le leng ngth th > 0 ) { prin print( t( "Ele "Eleme ment nt valu value e of " + elem elem.g .get etNa Name me() () + " is: is: " + node nodeVa Valu lue e ); } var child child = elem.get elem.getFirs FirstCh tChildE ildEleme lement() nt(); ; whil while( e( chil child d != null null ) { var nodeN nodeName ame = child child.g .getN etNam ame() e(); ; var nodeValu nodeValue e = child.g child.getNo etNodeVa deValue lue(); (); walkX walkXML( ML( child child ); child = child.getNextSi child.getNextSiblingEle blingElement(); ment(); } } print print( ( "Now "Now prin printin ting g the struc structur ture e of an XML XML file.. file...\ .\n" n" ); XMLSourc XMLSource e = XMLFile XMLFile; ; walkXML( walkXML( XMLSour XMLSource ce ); print print( ( "Now "Now prin printin ting g the struc structur ture e of an XML XML string string.. ...\n .\n" " ); XMLSourc XMLSource e = XMLStri XMLString; ng; walkXML( walkXML( XMLSour XMLSource ce );
XML.getNextAttribute(Element 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 following argument is valid for this method:
Element
String String
Contai Contains ns the the name name of of the the elem element ent you you want want the metho method d to use use as the starti starting ng positi position on when when searching for the first attribute.
76
Example This example example displays displays the first attribute attribute of any element element you select. It allows you to select an element element from two different input sources. sources. It requires the following following sample data: data:
A local XML file, such as a file called
" />" A valid XML string, such as:
C:\test.xml
containing the following sample data:
"" /* * * * *
Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. Use Use XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . Use Use sour source ceXM XMLS LStr trin ing g to stor store e a vali valid d XML XML stri string ng. . The The scri script pt sets sets the the conte content nt of XMLStr XMLString ing to sourc sourceX eXMLS MLStr tring ing. . The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */
var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test.xm t.xml", l", true true ); var sourceXMLString sourceXMLString = "" />"; ; var XMLSt XMLStri ring ng = new XML() XML(); ; XMLStrin XMLString g = XMLStri XMLString.s ng.setCo etConte ntent( nt( sourceXM sourceXMLSt LString ring ); var XMLSour XMLSource; ce; var TargetNode; TargetNode; var searchResults; searchResults; var attributeResult attributeResults; s; /* * * * * *
Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t conta contain ining ing the the eleme element nt. . This This func functi tion on assu assume mes s that that ther there e is only only one one inst instan ance ce of the the targ target et elem elemen ent t in the the sour source ce data data. . If it find finds s more more than than one one elem elemen ent t in the the data data, , it retu return rns s only onlyth the e firs first t inst instan ance ce of the the elem elemen ent. t. */
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null;; null;; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; }
77
} return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function function printFi printFindRe ndResult sults( s( target, target, searchRe searchResult sult ) { if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); return searchResult; searchResult; } else { prin print( t( "Can "Canno not t find find " + targ target et ); return return null; null; } } /* Crea Create te a func functi tion on to find find the the firs first t attr attrib ibut ute e of the the targ target et elem elemen ent t */ function findFirstAttribute( findFirstAttribute( sourceObject, targetNode ) { var startin startingNod gNode e = findTar findTargetE getEleme lement( nt( sourceO sourceObjec bject, t, targetN targetNode ode ); var firstAttribute firstAttribute = startingNode.ge startingNode.getFirstAt tFirstAttribute tribute(); (); if ( firs firstA tAtt ttri ribu bute te != null null ) { return firstAttribute; firstAttribute; } else { return return null; null; } } /* Crea Create te a func functi tion on to prin print t the the firs first t attr attrib ibut ute e of the the targ target et elem elemen ent t */ function printAttributeResult printAttributeResults( s( target, searchResult ) { if ( sear search chRe Resu sult lt != null null ) { var attributeName attributeName = searchResult.g searchResult.getNodeNa etNodeName(); me(); prin print( t( "The "The firs first t attr attrib ibut ute e of " + targ target et + " is: is: " + attr attrib ibut uteN eNam ame e ); return searchResult; searchResult; } else { prin print( t( "The "There re are are no attr attrib ibut utes es of " + targ target et ); return return null; null; } } /* Crea Create te a func functi tion on to find find the the next next attr attrib ibut ute e of the the targ target et elem elemen ent t */ function findNextAttribute( findNextAttribute( sourceObject, sourceObject, targetNode targetNode ) { var startin startingNod gNode e = findTar findTargetE getEleme lement( nt( sourceO sourceObjec bject, t, targetN targetNode ode ); var firstAttribute firstAttribute = startingNode.ge startingNode.getFirstAt tFirstAttribute tribute(); (); if ( firs firstA tAtt ttri ribu bute te != null null ) { var nextAttribute nextAttribute = startingNode.g startingNode.getNextAt etNextAttribute( tribute(); );
78
while while ( nextA nextAttr ttrib ibute ute != null null ) { var attributeName attributeName = nextAttribute.g nextAttribute.getNodeNa etNodeName(); me(); prin print( t( "The "The next next attr attrib ibut ute e of " + targ target etNo Node de + " is: is: " + attributeName attributeName ); nextAttribute nextAttribute = nextAttribute.g nextAttribute.getNextAt etNextAttribute( tribute(); ); } prin print( t( "The "There re are are no more more attr attrib ibut utes es of " + targ target etNo Node de ); return targetNode; targetNode; } else { return return null; null; } } /* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Targe TargetNo tNode de. . Run Run func functio tions ns
*/
print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "child1 "child1"; "; XMLSourc XMLSource e = XMLFile XMLFile; ; prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + Targ Target etNo Node de ); searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( TargetNode, TargetNode, searchResults searchResults ); attribut attributeRe eResult sults s = findFirs findFirstAt tAttrib tribute( ute( XMLSourc XMLSource, e, TargetNo TargetNode de ); printAttributeR printAttributeResults( esults( TargetNode, TargetNode, attributeResult attributeResults s ); findNextAttribu findNextAttribute( te( XMLSource, XMLSource, TargetNode TargetNode ); /* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Targe TargetNo tNode de. . Run Run func functio tions ns
*/
print print( ( "Pro "Proces cessi sing ng XML XML from from XMLSt XMLStri ring. ng... .. \n" \n" ); TargetNo TargetNode de = "child2 "child2"; "; XMLSourc XMLSource e = XMLStri XMLString; ng; prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + Targ Target etNo Node de ); searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( TargetNode, TargetNode, searchResults searchResults ); attribut attributeRe eResult sults s = findFirs findFirstAt tAttrib tribute( ute( XMLSourc XMLSource, e, TargetNo TargetNode de ); printAttributeR printAttributeResults( esults( TargetNode, TargetNode, attributeResult attributeResults s ); findNextAttribu findNextAttribute( te( XMLSource, XMLSource, TargetNode TargetNode );
XML.getNextSiblingElement(Element 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: getNextSiblingElement() Or getNextSiblingElement(Element getNextSiblingElement(Element ). ). The following argument is valid for this method: at Element
String String
Contai Contains ns the name name of the elemen elementt you you want want the the method method to use use as as the the starti starting ng positi position on when searching for the next sibling element.
79
Example This example example displays displays the next sibling element element of any element you select. select. It allows you to select an element element from two different input input sources. It requires the following following sample data:
A local XML file, such as a file called
" />" A valid XML string, such as:
C:\test.xml
containing the following sample data:
"" /* * * * *
Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. Use Use XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . Use Use sour source ceXM XMLS LStr trin ing g to stor store e a vali valid d XML XML stri string ng. . The The scri script pt sets sets the the conte content nt of XMLStr XMLString ing to sourc sourceX eXMLS MLStr tring ing. . The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */
var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test.xm t.xml", l", true true ); var sourceXMLString sourceXMLString = ""; />"; var XMLSt XMLStri ring ng = new XML() XML(); ; XMLStrin XMLString g = XMLStri XMLString.s ng.setCo etConte ntent( nt( sourceXM sourceXMLSt LString ring ); var XMLSour XMLSource; ce; var TargetNode; TargetNode; var searchResults; searchResults; var siblingResults; siblingResults; /* * * * * *
Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t conta contain ining ing the the eleme element nt. . This This func functi tion on assu assume mes s that that ther there e is only only one one inst instan ance ce of the the targ target et elem elemen ent t in the the sour source ce data data. . If it find finds s more more than than one one elem elemen ent t in the the data data, , it retur returns ns only only the firs first t inst instan ance ce of the the elem elemen ent. t. */
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; }
80
} return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function function printFi printFindRe ndResult sults( s( target, target, searchRe searchResult sult ) { if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); return searchResult; searchResult; } else { prin print( t( "Can "Canno not t find find " + targ target et ); return return null; null; } } /* Crea Create te a func functi tion on to find find the the next next sibl siblin ing g elem elemen ent t of the the targ target et * elemen ment */ */ function function findNex findNextSib tSibling ling( ( sourceO sourceObjec bject, t, targetNo targetNode de ) { var startin startingNod gNode e = findTar findTargetE getEleme lement( nt( sourceO sourceObjec bject, t, targetN targetNode ode ); var nextSibling nextSibling = startingNode.get startingNode.getNextSib NextSiblingElem lingElement(); ent(); if ( next nextSi Sibl blin ing g != null null ) { return nextSibling; nextSibling; } else { return return null; null; } } /* Crea Create te a func functi tion on to prin print t the the firs first t attr attrib ibut ute e of the the targ target et * elemen ment */ */ function function printSi printSiblin blingRes gResults ults( ( target, target, searchR searchResul esult t ) { if ( sear search chRe Resu sult lt != null null ) { var childName childName = searchResult.ge searchResult.getNodeNa tNodeName(); me(); prin print( t( "The "The next next sibl siblin ing g elem elemen ent t of " + targ target et + " is: is: " + childNam childName e ); } else { prin print( t( "The "There re are are no sibl siblin ing g elem elemen ents ts of " + targ target et ); } } /* Set Set vari variabl ables es to searc search h the the XMLF XMLFile ile for the the Targe TargetN tNode ode. . * Run functio functions ns findTar findTargetE getEleme lement, nt, printFi printFindRe ndResul sults, ts, findAttr findAttribut ibute, e, * and and prin printAt tAttr tribu ibute teRes Result ults s on the the XMLF XMLFile ile and Targe TargetNo tNode de */ print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "child3 "child3"; "; XMLSourc XMLSource e = XMLFile XMLFile; ; prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + Targ Target etNo Node de ); searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode );
81
printFindResult printFindResults( s( TargetNode, TargetNode, searchResults searchResults ); siblingR siblingResu esults lts = findNex findNextSib tSibling ling( ( XMLSourc XMLSource, e, TargetNo TargetNode de ); printSiblingRes printSiblingResults( ults( TargetNode, TargetNode, siblingResults siblingResults ); /* Set Set vari variabl ables es to searc search h the the XMLS XMLStri tring ng for for the Targe TargetNo tNode de. . * Run functio functions ns findTar findTargetE getEleme lement, nt, printFi printFindRe ndResul sults, ts, findAttr findAttribut ibute, e, * and and prin printAt tAttr tribu ibute teRes Result ults s on the the XMLS XMLStri tring ng and and Targ TargetN etNod ode e */ print print( ( "Pro "Proces cessi sing ng XML XML from from XMLSt XMLStri ring. ng... .. \n" \n" ); TargetNo TargetNode de = "child1 "child1"; "; XMLSourc XMLSource e = XMLStri XMLString; ng; prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + Targ Target etNo Node de ); searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( TargetNode, TargetNode, searchResults searchResults ); siblingR siblingResu esults lts = findNex findNextSib tSibling ling( ( XMLSourc XMLSource, e, TargetNo TargetNode de ); printSiblingRes printSiblingResults( ults( TargetNode, TargetNode, siblingResults siblingResults );
XML.getNodeName() This method returns a string representing the name of the current element or attribute; or returns null if the current current node has no name. name. Use the other other XML getxxx getxxx methods methods to navigate through an XML document. The syntax is: getNodeName() No arguments are passed. Example This example example displays displays the names of the elements elements and attributes attributes in an XML document. document. It requires requires the following sample data:
A local XML file, such as a file called
" />" A valid XML string, such as:
C:\test.xml
containing the following sample data:
"0123 "0123" document>" /* * * * *
Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. Use Use XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . Use Use sour source ceXM XMLS LStr trin ing g to stor store e a vali valid d XML XML stri string ng. . The The scri script pt sets sets the the conte content nt of XMLStr XMLString ing to sourc sourceX eXMLS MLStr tring ing. . The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */
var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test.xm t.xml", l", true true ); var sourceX sourceXMLSt MLString ring = "0123"; var XMLSt XMLStri ring ng = new XML() XML(); ; XMLStrin XMLString g = XMLStri XMLString.s ng.setCo etConte ntent( nt( sourceXM sourceXMLSt LString ring ); var XMLSour XMLSource; ce; funct function ion walkX walkXML ML( ( elem elem ) { print( print( "Element "Element " + elem.ge elem.getNod tNodeNam eName() e() ); var node node = elem.ge elem.getFir tFirstAt stAttrib tribute( ute(); );
82
whil while( e( node node != null null ) { var attrNa attrName me = node. node.ge getNo tNode deNam Name( e(); ); var attrValu attrValue e = node.ge node.getNod tNodeVal eValue( ue(); ); prin print( t( "Att "Attri ribu bute te " + attr attrNa Name me + " = " + attr attrVa Valu lue e ); node = elem.getNextAtt elem.getNextAttribute( ribute(); ); } var nodeVal nodeValue ue = elem.get elem.getNod NodeVal eValue() ue(); ; if ( type typeof of node nodeVa Valu lue e == "str "strin ing" g" && node nodeVa Valu lue. e.le leng ngth th > 0 ) { prin print( t( "Ele "Eleme ment nt valu value e of " + elem elem.g .get etNo Node deNa Name me() () + " is: is: " + nodeValu nodeValue e ); } var child child = elem.get elem.getFirs FirstCh tChildE ildEleme lement() nt(); ; whil while( e( chil child d != null null ) { var nodeNa nodeName me = child.ge child.getNod tNodeNam eName(); e(); var nodeValu nodeValue e = child.g child.getNo etNodeVa deValue lue(); (); walkX walkXML( ML( child child ); child = child.getNextSi child.getNextSiblingEle blingElement(); ment(); } } print print( ( "Now "Now prin printin ting g the struc structur ture e of an XML XML file.. file...\ .\n" n" ); XMLSourc XMLSource e = XMLFile XMLFile; ; walkXML( walkXML( XMLSour XMLSource ce ); print print( ( "Now "Now prin printin ting g the struc structur ture e of an XML XML string string.. ...\n .\n" " ); XMLSourc XMLSource e = XMLStri XMLString; ng; walkXML( walkXML( XMLSour XMLSource ce );
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 DOM type. (See the W3C W3C Web site (http://www.w3c.org (http://www.w3c.org)) for a complete listing of XML DOM node types by integer.) integer.) This method method returns a type error if applied to anything anything other than an XML object. This limits this method method to elements elements and attributes attributes because the Service Manager XML object cannot cannot represent represent element values values as an XML object. Use the other XML.get XML.getxxx xxx methods methods to navigate through an XML document. The syntax is getNodeType() No arguments are passed. Example This example example displays displays the XML DOM types of the elements elements and attributes attributes in an XML document. document. It requires a local XML file, such as a file called C:\test.xml containing the following sample data: "value1value1" function function visitEl visitElemen ement( t( elem ) { prin print( t( "Ele "Eleme ment nt " + elem elem.g .get etQu Qual alif ifie iedN dNam ame( e() ) + " is of type type " + elem.getNodeTyp elem.getNodeType() e() );
83
/* Print Print attr attribu ibute tes s for for this this eleme element nt */ var node node = elem.ge elem.getFir tFirstAt stAttrib tribute( ute(); ); whil while( e( node node != null null ) { var attrName attrName = node.getQu node.getQuali alified fiedName Name(); (); var attrValu attrValue e = node.ge node.getNod tNodeVal eValue( ue(); ); prin print( t( "Att "Attri ribu bute te " + attr attrNa Name me + "=" "=" + attr attrVa Valu lue e + " and and is of type type " + node.ge node.getNod tNodeTyp eType() e() ); node = elem.getNextAtt elem.getNextAttribute( ribute(); ); } /* Print Print poss possibl ible e elemen element t value value */ var nodeVal nodeValue ue = elem.get elem.getNod NodeVal eValue() ue(); ; if ( type typeof of node nodeVa Valu lue e == "str "strin ing" g" && node nodeVa Valu lue. e.le leng ngth th > 0 ) { prin print( t( "Ele "Eleme ment nt valu value e is " + node nodeVa Valu lue e + " and and is of type type " + elem.getNodeTyp elem.getNodeType() e() ); } /* Now Now prin print t chil child d elem elemen ents ts */ var child child = elem.get elem.getFirs FirstCh tChildE ildEleme lement() nt(); ; whil while( e( chil child d != null null ) { var nodeNa nodeName me = child.ge child.getNod tNodeNam eName(); e(); var nodeValu nodeValue e = child.g child.getNo etNodeVa deValue lue(); (); visitEle visitElement ment( ( child child ); child = child.getNextSi child.getNextSiblingEle blingElement(); ment(); } } var var xmlO xmlObj bj = new new XML( XML(); ); xmlObj.s xmlObj.setC etConte ontent( nt( "c:\\te "c:\\test.x st.xml", ml", true ); visitElement( visitElement( xmlObj.getDocum xmlObj.getDocumentEleme entElement() nt() );
XML.getNodeValue() The method returns a string representing the value of the current XML element; or returns null if the current current node has no value. value. This method method requires you use the other XML get methods to navigate navigate through an XML document. The syntax is: getNodeValue() No arguments are passed. Example This example example displays displays the value of the elements elements in an XML document. document. It requires a local XML file, such as a file called C:\test02.xml containing the following sample data: "value1< "value1 parent2>" " /* * * * *
Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. Use Use XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . Use Use sour source ceXM XMLS LStr trin ing g to stor store e a vali valid d XML XML stri string ng. . The The scri script pt sets sets the the conte content nt of XMLStr XMLString ing to sourc sourceX eXMLS MLStr tring ing. . The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */
var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test02. t02.xml xml", ", true ); var XMLSour XMLSource; ce; var TargetNode; TargetNode;
84
/* * * * * *
Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t conta contain ining ing the the eleme element nt. . This This func functi tion on assu assume mes s that that ther there e is only only one one inst instan ance ce of the the targ target et elem elemen ent t in the the sour source ce data data. . If it find finds s more more than than one one elem elemen ent t in the the data data, , it retur returns ns only only the firs first t inst instan ance ce of the the elem elemen ent. t. */
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; } } return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function printFindResults( printFindResults( searchResult, searchResult, targetNode targetNode ) { prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + targ target etNo Node de ); if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); findValu findValue( e( searchR searchResul esult, t, targetN targetNode ode ); return searchResult; searchResult; } else { prin print( t( "Can "Canno not t find find " + targ target et ); return return null; null; } } /* Crea Create te a func functi tion on to find find the the pare parent nt node node elem elemen ent t of the the targ target et * elemen ment */ */ function function findVal findValue( ue( sourceOb sourceObject ject, , targetNo targetNode de ) { var valueFound valueFound = sourceObject.ge sourceObject.getNodeVal tNodeValue(); ue(); if ( valu valueF eFou ound nd.l .len engt gth h >= 1 )
85
{ prin print( t( "The "The valu value e of " + targ target etNo Node de + " is: is: " + valu valueF eFou ound nd ); return valueFound; valueFound; } else { prin print( t( "The "There re is no valu value e for for " + targ target etNo Node de ); valueFou valueFound nd = null; null; return valueFound; valueFound; } }
/* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Target TargetNod Node. e. Run Run func functio tions ns. .
*/
print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "parent "parent1"; 1"; XMLSourc XMLSource e = XMLFile XMLFile; ; searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( searchResults, searchResults, TargetNode TargetNode ); /* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Target TargetNod Node. e. Run Run func functio tions ns. . print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "parent "parent2"; 2"; XMLSourc XMLSource e = XMLFile XMLFile; ; searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( searchResults, searchResults, TargetNode TargetNode );
*/
XML.getParentNode(Element 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: getParentNode() Or getParentNode(Element getParentNode(Element ) The following argument is valid for this method: at Node
String String
Contai Contains ns the name name of the elemen elementt you you want want the the method method to use use as as the the starti starting ng positi position on when searching for the parent node element.
Example This example example displays displays the parent node element of any element you select. select. The example example allows you to select select an element element from two different different input sources. sources. It requires the following following sample data:
A local XML file, such as a file called
" />" A valid XML string, such as:
C:\test.xml
containing the following sample data:
86
"" /* * * * *
Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. Use Use XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . Use Use sour source ceXM XMLS LStr trin ing g to stor store e a vali valid d XML XML stri string ng. . The The scri script pt sets sets the the conte content nt of XMLStr XMLString ing to sourc sourceX eXMLS MLStr tring ing. . The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */
var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test.xm t.xml", l", true true ); var sourceXMLString sourceXMLString = ""; />"; var XMLSt XMLStri ring ng = new XML() XML(); ; XMLStrin XMLString g = XMLStri XMLString.s ng.setCo etConte ntent( nt( sourceXM sourceXMLSt LString ring ); var XMLSour XMLSource; ce; var TargetNode; TargetNode; var searchResults; searchResults; var parentResults; parentResults; /* * * * * *
Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t conta contain ining ing the the eleme element nt. . This This func functi tion on assu assume mes s that that ther there e is only only one one inst instan ance ce of the the targ target et elem elemen ent t in the the sour source ce data data. . If it find finds s more more than than one one elem elemen ent t in the the data data, , it retur returns ns only only the firs first t inst instan ance ce of the the elem elemen ent. t. */
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; } } return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function function printFi printFindRe ndResult sults( s( target, target, searchRe searchResult sult ) { if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e();
87
prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); return searchResult; searchResult; } else { prin print( t( "Can "Canno not t find find " + targ target et ); return return null; null; } } /* Crea Create te a func functi tion on to find find the the pare parent nt node node of the the targ target et elem elemen ent t */ function function findPar findParent( ent( sourceOb sourceObject ject, , targetNo targetNode de ) { var startin startingNod gNode e = findTar findTargetE getEleme lement( nt( sourceO sourceObjec bject, t, targetN targetNode ode ); var parentNode parentNode = startingNode.ge startingNode.getParentN tParentNode(); ode(); if ( pare parent ntNo Node de != null null ) { return parentNode; parentNode; } else { return return null; null; } } /* Crea Create te a func functi tion on to prin print t the the firs first t attr attrib ibut ute e of the the targ target et * elemen ment */ */ function function printPa printParent rentResu Results( lts( target, target, searchR searchResul esult t ) { if ( sear search chRe Resu sult lt != null null ) { var parentName parentName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "The "The pare parent nt node node elem elemen ent t of " + targ target et + " is: is: " + parentNa parentName me ); } else { prin print( t( "The "There re is no pare parent nt node node elem elemen ent t of " + targ target et ); } } /* Set Set vari variabl ables es to searc search h the the XMLF XMLFile ile for the the Targe TargetN tNode ode. . * Run functio functions ns findTar findTargetE getEleme lement, nt, printFi printFindRe ndResul sults, ts, findAttr findAttribut ibute, e, * and and prin printAt tAttr tribu ibute teRes Result ults s on the the XMLF XMLFile ile and Targe TargetNo tNode de */ print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "child3 "child3"; "; XMLSourc XMLSource e = XMLFile XMLFile; ; prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + Targ Target etNo Node de ); searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( TargetNode, TargetNode, searchResults searchResults ); parentRe parentResul sults ts = findPare findParent( nt( XMLSour XMLSource, ce, TargetNo TargetNode de ); printParentResu printParentResults( lts( TargetNode, TargetNode, parentResults parentResults ); /* Set Set vari variabl ables es to searc search h the the XMLS XMLStri tring ng for for the Targe TargetNo tNode de. . * Run functio functions ns findTar findTargetE getEleme lement, nt, printFi printFindRe ndResul sults, ts, findAttr findAttribut ibute, e, * and and prin printAt tAttr tribu ibute teRes Result ults s on the the XMLS XMLStri tring ng and and Targ TargetN etNod ode e */ print print( ( "Pro "Proces cessi sing ng XML XML from from XMLSt XMLStri ring. ng... .. \n" \n" );
88
TargetNo TargetNode de = "child1 "child1"; "; XMLSourc XMLSource e = XMLStri XMLString; ng; prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + Targ Target etNo Node de ); searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( TargetNode, TargetNode, searchResults searchResults ); parentRe parentResul sults ts = findPare findParent( nt( XMLSour XMLSource, ce, TargetNo TargetNode de ); printParentResu printParentResults( lts( TargetNode, TargetNode, parentResults parentResults );
XML.getPrefix() This method returns a string representing the namespace value of the current node (element or attribute) attribute);; or returns returns null if the current node has no namespace namespace value.. Use the other XML.get XML.getxxx xxx methods to navigate through an XML document. The syntax is: getPrefix() No arguments arguments are are passed. passed. Example This example example displays the namespace namespace value of the elements elements and attributes attributes in an XML document. It requires a local XML file, such as a file called C:\namespace.xml containing the following sample data: /* * * * *
Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. Use Use XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . Use Use sour source ceXM XMLS LStr trin ing g to stor store e a vali valid d XML XML stri string ng. . The The scri script pt sets sets the the conte content nt of XMLStr XMLString ing to sourc sourceX eXMLS MLStr tring ing. . The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */
var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\nam "C:\\namespa espace. ce.xml" xml", , true true ); var XMLSour XMLSource; ce; var TargetNode; TargetNode; var searchResults; searchResults; var prefixResults; prefixResults; var firstAttribute; firstAttribute; var attributeResult attributeResults; s; /* * * * * *
Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t conta contain ining ing the the eleme element nt. . This This fuct fuctio ion n assu assume mes s that that ther there e is only only one one inst instan ance ce of the the targ target et elem elemen ent t in the the sour source ce data data. . If it find finds s more more than than one one elem elemen ent t in the the data data it only only retu return rns s the the firs first t inst instan ance ce of the the elem elemen ent. t. */
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null)
89
{ node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; } } return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function printFindResults( printFindResults( searchResult, searchResult, targetNode targetNode ) { prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + targ target etNo Node de ); if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); findPref findPrefix( ix( searchR searchResul esult, t, targetN targetNode ode ); return searchResult; searchResult; } else { prin print( t( "Can "Canno not t find find " + targ target et ); return return null; null; } } /* Crea Create te a func functi tion on to find find the the pare parent nt node node elem elemen ent t of the the targ target et element element */ function function findPre findPrefix( fix( sourceOb sourceObject ject, , targetNo targetNode de ) { var prefixFound prefixFound = sourceObject.get sourceObject.getPrefix( Prefix(); ); if ( prefi prefixF xFoun ound. d.len lengt gth h >= 1 ) { prin print( t( "The "The name namesp spac ace e pref prefix ix of " + targ target etNo Node de + " is: is: " + prefixFo prefixFound und ); return prefixFound; prefixFound; } else { prin print( t( "The "There re is no name namesp spac ace e pref prefix ix of " + targ target etNo Node de ); prefixFo prefixFound und = null; null; return prefixFound; prefixFound; } } /* Crea Create te a func functi tion on to find find the the firs first t attr attrib ibut ute e of the the targ target et elem elemen ent t */ function findFirstAttribute( findFirstAttribute( sourceObject, targetNode ) { var startin startingNod gNode e = findTar findTargetE getEleme lement( nt( sourceO sourceObjec bject, t, targetN targetNode ode ); var firstAttribute firstAttribute = startingNode.ge startingNode.getFirstAt tFirstAttribute tribute(); ();
90
if ( firs firstA tAtt ttri ribu bute te != null null ) { var attributeName attributeName = firstAttribute firstAttribute.getNode .getNodeName(); Name(); prin print( t( "The "The firs first t attr attrib ibut ute e of " + targ target etNo Node de + " is: is: " + attributeName attributeName ); findPrefix( findPrefix( firstAttribute, firstAttribute, targetNode ); return firstAttribute; firstAttribute; } else { prin print( t( "The "There re are are no attr attrib ibut utes es of " + targ target etNo Node de ); return return null; null; } } /* Crea Create te a func functi tion on to find find the the next next attr attrib ibut ute e of the the targ target et elem elemen ent t */ function findNextAttribute( findNextAttribute( sourceObject, sourceObject, targetNode targetNode ) { var startin startingNod gNode e = findTar findTargetE getEleme lement( nt( sourceO sourceObjec bject, t, targetN targetNode ode ); var firstAttribute firstAttribute = startingNode.ge startingNode.getFirstAt tFirstAttribute tribute(); (); if ( firs firstA tAtt ttri ribu bute te != null null ) { var nextAttribute nextAttribute = startingNode.g startingNode.getNextAt etNextAttribute( tribute(); ); while while ( nextA nextAttr ttrib ibute ute != null null ) { var attributeName attributeName = nextAttribute.g nextAttribute.getNodeNa etNodeName(); me(); prin print( t( "The "The next next attr attrib ibut ute e of " + targ target etNo Node de + " is: is: " + attributeName attributeName ); findPrefix( findPrefix( nextAttribute, nextAttribute, targetNode ); nextAttribute nextAttribute = nextAttribute.g nextAttribute.getNextAt etNextAttribute( tribute(); ); } prin print( t( "The "There re are are no more more attr attrib ibut utes es of " + targ target etNo Node de ); return targetNode; targetNode; } else { return return null; null; } } /* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Target TargetNod Node. e. Run Run func functio tions ns. . */ print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "elemen "element1"; t1"; XMLSourc XMLSource e = XMLFile XMLFile; ; searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( searchResults, searchResults, TargetNode TargetNode ); /* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Target TargetNod Node. e. Run Run func functio tions ns. . print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "docume "document"; nt"; XMLSourc XMLSource e = XMLFile XMLFile; ; searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( searchResults, searchResults, TargetNode TargetNode ); findFirstAttrib findFirstAttribute( ute( XMLSource, XMLSource, TargetNode TargetNode ); findNextAttribu findNextAttribute( te( XMLSource, XMLSource, TargetNode TargetNode );
*/
XML.getQualifiedName() This method, which is a synonym for getNodeName(), returns a string representing the name of the current current element or attribute; attribute; or returns null if the current node has no name. Use the other XML.get XML.getxxx xxx methods to navigate through an XML document.
91
The syntax for this method is: getQualifiedName() No arguments are passed. Example This example example displays displays the names of the elements elements and attributes attributes in an XML document. document. It requires requires a local XML file, such as a file called C:\namespace.xml containing the following sample data: /* Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. * Use Use XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . * The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */ var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\nam "C:\\namespa espace. ce.xml" xml", , true true ); var XMLSour XMLSource; ce; function function nsXMLWa nsXMLWalk( lk( elem ) { print( print( "Element "Element " + elem.ge elem.getQua tQualifi lifiedNa edName( me() ) ); var node node = elem.ge elem.getFir tFirstAt stAttrib tribute( ute(); ); whil while( e( node node != null null ) { var attrName attrName = node.getQu node.getQuali alified fiedName Name(); (); var attrValu attrValue e = node.ge node.getNod tNodeVal eValue( ue(); ); prin print( t( "Att "Attri ribu bute te " + attr attrNa Name me + " = " + attr attrVa Valu lue e ); node = elem.getNextAtt elem.getNextAttribute( ribute(); ); } var nodeVal nodeValue ue = elem.get elem.getNod NodeVal eValue() ue(); ; if ( type typeof of node nodeVa Valu lue e == "str "strin ing" g" && node nodeVa Valu lue. e.le leng ngth th > 0 ) { prin print( t( "Ele "Eleme ment nt valu value e of " + elem elem.g .get etQu Qual alif ifie iedN dNam ame( e() ) + " is: is: " + nodeValu nodeValue e ); } var child child = elem.get elem.getFirs FirstCh tChildE ildEleme lement() nt(); ; whil while( e( chil child d != null null ) { var nodeName nodeName = child.g child.getQu etQualif alified iedName Name(); (); var nodeValu nodeValue e = child.g child.getNo etNodeVa deValue lue(); (); nsXMLWal nsXMLWalk( k( child child ); child = child.getNextSi child.getNextSiblingEle blingElement(); ment(); } } funct function ion walkX walkXML ML( ( elem elem ) { print print( ( "Elem "Element ent " + elem. elem.ge getNa tName me() () ); var node node = elem.get elem.getFirs FirstAt tAttrib tribute( ute(); ); whil while( e( node node != null null ) { var attrN attrName ame = node. node.ge getNa tName me(); (); var attrValu attrValue e = node.ge node.getNod tNodeVal eValue( ue(); );
92
prin print( t( "Att "Attri ribu bute te " + attr attrNa Name me + " = " + attr attrVa Valu lue e ); node = elem.getNextAtt elem.getNextAttribute( ribute(); ); } var nodeVal nodeValue ue = elem.get elem.getNod NodeVal eValue() ue(); ; if ( type typeof of node nodeVa Valu lue e == "str "strin ing" g" && node nodeVa Valu lue. e.le leng ngth th > 0 ) { prin print( t( "Ele "Eleme ment nt valu value e of " + elem elem.g .get etNa Name me() () + " is: is: " + node nodeVa Valu lue e ); } var child child = elem.get elem.getFirs FirstCh tChildE ildEleme lement() nt(); ; whil while( e( chil child d != null null ) { var nodeN nodeName ame = child child.g .getN etNam ame() e(); ; var nodeValu nodeValue e = child.g child.getNo etNodeVa deValue lue(); (); walkX walkXML( ML( child child ); child = child.getNextSi child.getNextSiblingEle blingElement(); ment(); } } print print( ( "Now "Now prin printin ting g the struc structur ture e of an XML XML file file with with qual qualifi ified ed names... names...\n" \n" ); XMLSourc XMLSource e = XMLFile XMLFile; ; nsXMLWal nsXMLWalk( k( XMLSourc XMLSource e ); print print( ( "Now "Now prin printin ting g the struc structur ture e of an XML XML file file with without out quali qualifie fied d names... names...\n" \n" ); XMLSourc XMLSource e = XMLFile XMLFile; ; walkXML( walkXML( XMLSour XMLSource ce );
XML.getText() This method, which is a synonym for getNodeValue(), returns a string representing the value of the current current XML element; or returns null null if the current node node has no value. value. Use the other XML.get XML.getxxx xxx methods to navigate through an XML document. The syntax is: getText() No arguments are passed. Example This example example displays displays the value of the elements elements in an XML document. document. It requires a local XML file, such as a file called " C:\test02.xml" containing the following sample data: "value1< "value1 parent2>" " /* * * * *
Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. Use Use XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . Use Use sour source ceXM XMLS LStr trin ing g to stor store e a vali valid d XML XML stri string ng. . The The scri script pt sets sets the the conte content nt of XMLStr XMLString ing to sourc sourceX eXMLS MLStr tring ing. . The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */
var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test02. t02.xml xml", ", true ); var XMLSour XMLSource; ce; var TargetNode; TargetNode;
93
/* * * * * *
Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t conta contain ining ing the the eleme element nt. . This This func functi tion on assu assume mes s that that ther there e is only only one one inst instan ance ce of the the targ target et elem elemen ent t in the the sour source ce data data. . If it find finds s more more than than one one elem elemen ent t in the the data data, , it retur returns ns only only the firs first t inst instan ance ce of the the elem elemen ent. t. */
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; } } return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function printFindResults( printFindResults( searchResult, searchResult, targetNode targetNode ) { prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + targ target etNo Node de ); if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); findValu findValue( e( searchR searchResul esult, t, targetN targetNode ode ); return searchResult; searchResult; } else { prin print( t( "Can "Canno not t find find " + targ target et ); return return null; null; } } /* Crea Create te a func functi tion on to find find the the pare parent nt node node elem elemen ent t of the the targ target et * elemen ment */ */ function function findVal findValue( ue( sourceOb sourceObject ject, , targetNo targetNode de ) { var valueFo valueFound und = sourceOb sourceObject ject.ge .getTex tText(); t(); if ( valu valueF eFou ound nd.l .len engt gth h >= 1 ) { prin print( t( "The "The valu value e of " + targ target etNo Node de + " is: is: " + valu valueF eFou ound nd );
94
return valueFound; valueFound; } else { prin print( t( "The "There re is no valu value e for for " + targ target etNo Node de ); valueFou valueFound nd = null; null; return valueFound; valueFound; } } /* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Target TargetNod Node. e. Run Run func functio tions ns. . print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "parent "parent1"; 1"; XMLSourc XMLSource e = XMLFile XMLFile; ; searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( searchResults, searchResults, TargetNode TargetNode );
*/
/* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Target TargetNod Node. e. Run Run func functio tions ns. . print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "parent "parent2"; 2"; XMLSourc XMLSource e = XMLFile XMLFile; ; searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( searchResults, searchResults, TargetNode TargetNode );
*/
XML.getValue() This method, which is a synonym for getNodeValue(), returns a string representing the value of the current current XML element; or returns null null if the current node node has no value. value. Use the other XML.get XML.getxxx xxx methods to navigate through an XML document. The syntax is: getValue() No arguments are passed. Example This example example displays displays the value of the elements elements in an XML document. document. It requires a local XML file, such as a file called " C:\test02.xml" containing the following as sample data: "value1< "value1 parent2>" " /* * * * *
Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. Use Use XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . Use Use sour source ceXM XMLS LStr trin ing g to stor store e a vali valid d XML XML stri string ng. . The The scri script pt sets sets the the conte content nt of XMLStr XMLString ing to sourc sourceX eXMLS MLStr tring ing. . The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */
var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test02. t02.xml xml", ", true ); var XMLSour XMLSource; ce; var TargetNode; TargetNode; /* * * * * *
Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t conta contain ining ing the the eleme element nt. . This This func functi tion on assu assume mes s that that ther there e is only only one one inst instan ance ce of the the targ target et elem elemen ent t in the the sour source ce data data. . If it find finds s more more than than one one elem elemen ent t in the the data data, , it retur returns ns only only the firs first t inst instan ance ce of the the elem elemen ent. t. */
95
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; } } return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function printFindResults( printFindResults( searchResult, searchResult, targetNode targetNode ) { prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + targ target etNo Node de ); if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); findValu findValue( e( searchR searchResul esult, t, targetN targetNode ode ); return searchResult; searchResult; } else { prin print( t( "Can "Canno not t find find " + targ target et ); return return null; null; } } /* Crea Create te a func functi tion on to find find the the pare parent nt node node elem elemen ent t of the the targ target et * elemen ment */ */ function function findVal findValue( ue( sourceOb sourceObject ject, , targetNo targetNode de ) { var valueFound valueFound = sourceObject.ge sourceObject.getValue() tValue(); ; if ( valu valueF eFou ound nd.l .len engt gth h >= 1 ) { prin print( t( "The "The valu value e of " + targ target etNo Node de + " is: is: " + valu valueF eFou ound nd ); return valueFound; valueFound; } else { prin print( t( "The "There re is no valu value e for for " + targ target etNo Node de ); valueFou valueFound nd = null; null;
96
return valueFound; valueFound; } } /* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Target TargetNod Node. e. Run Run func functio tions ns. . print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "parent "parent1"; 1"; XMLSourc XMLSource e = XMLFile XMLFile; ; searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( searchResults, searchResults, TargetNode TargetNode );
*/
/* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Target TargetNod Node. e. Run Run func functio tions ns. . print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "parent "parent2"; 2"; XMLSourc XMLSource e = XMLFile XMLFile; ; searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( searchResults, searchResults, TargetNode TargetNode );
*/
XML.importNode(name XML.importNode(name ) This method returns an XML object containing a copy of the source XML node; or returns null if the method method cannot import a copy of the node. It requires requires two existing XML objects objects with document elements: elements: one is the source source XML object and the other is the target target XML document. document. This method method does not update update either the source or the target target XML object. Instead, Instead, you use the appendNode appendNode method to add the imported node into the target XML document. The syntax is: importNode( name ) name ) The following argument is valid for this method:
name
String String
Specif Specifies ies the XML node node name name you you want to copy copy from from the source source XML XML obje object. ct. Must Must cont contain ain characters valid for XML (for example, the string cannot include the characters < or > except as XML entities such as < and >).
Example This example example imports imports an XML node from one XML object to another. another. It requires the following following sample sample data:
A local XML file, such as a file called " C:\test.xml" containing:
" />" An XML object, such as an object containing: ""
var XMLFil XMLFile e = new new XML() XML(); ; var XMLOb XMLObje ject ct = new XML() XML(); ; var TargetNode; TargetNode; function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent();
97
if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; } } return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function function printFi printFindRe ndResult sults( s( target, target, searchRe searchResult sult ) { if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); return searchResult; searchResult; } else { prin print( t( "Can "Canno not t find find " + targ target et ); return return null; null; } } function function importN importNewNo ewNode( de( xmlSourc xmlSource, e, xmlTarge xmlTarget, t, node node ) { print print( ( "The "The XML sourc source e obje object ct is:\n is:\n" " + xmlSo xmlSour urce ce ); prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + node node ); var FoundNo FoundNode de = findTarg findTargetE etEleme lement( nt( xmlSour xmlSource, ce, node ); printFi printFindRe ndResult sults( s( node, node, FoundNo FoundNode de ); print print( ( "The "The XML targe target t obje object ct is:\n is:\n" " + xmlTa xmlTarg rget et ); print print( ( "Impo "Importi rting ng " + Found FoundNod Node e + " into into XML targe target t obje object. ct... .." " ); var NewNode NewNode = xmlTarg xmlTarget.i et.impor mportNo tNode( de( FoundNod FoundNode e ); prin print( t( "The "The XML XML targ target et obje object ct ream reamin ins s unch unchan ange ged: d: " + xmlT xmlTar arge get t ); print print( ( "Appe "Appendi nding ng " + Found FoundNod Node e + " into into XML targe target t obje object. ct... .."); "); var appende appendedNod dNode e = xmlTarg xmlTarget.a et.appen ppendNo dNode( de( NewNode NewNode ); prin print( t( "The "The new new XML XML targ target et objec object t is: is: " + xmlT xmlTar arge get t ); } XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test.xm t.xml", l", true true ); XMLObjec XMLObject t = XMLObje XMLObject.s ct.setCo etConte ntent( nt( " nt> ent>" " ); TargetNo TargetNode de = "parent "parent1"; 1"; importNe importNewNo wNode( de( XMLFile, XMLFile, XMLObjec XMLObject, t, TargetNo TargetNode de );
98
XML.isDocumentElement() This method returns true if the current element is the Document Object Model (DOM) document element element (the "root" node of the XML document); document); and returns returns false if it is not. Use the XML.get XML.getxxx xxx methods to navigate through an XML document. The syntax is: isDocumentElement() No arguments are passed. Example This example example checks whether whether the selected element element is the DOM document document element. It requires requires a local XML file, such as a file called C:\test02.xml containing: "value1< "value1 parent2>" " /* * * * *
Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. Use Use XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . Use Use sour source ceXM XMLS LStr trin ing g to stor store e a vali valid d XML XML stri string ng. . The The scri script pt sets sets the the conte content nt of XMLStr XMLString ing to sourc sourceX eXMLS MLStr tring ing. . The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */
var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test02. t02.xml xml", ", true ); var XMLSour XMLSource; ce; var TargetNode; TargetNode; /* * * * * *
Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t conta contain ining ing the the eleme element nt. . This This func functi tion on assu assume mes s that that ther there e is only only one one inst instan ance ce of the the targ target et elem elemen ent t in the the sour source ce data data. . If it find finds s more more than than one one elem elemen ent t in the the data data it retur returns ns only only the the firs first t inst instan ance ce of the the elem elemen ent. t. */
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; } }
99
return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function printFindResults( printFindResults( searchResult, searchResult, targetNode targetNode ) { print print(" ("The The targe target t eleme element nt we are are looki looking ng for for is: " + targe targetN tNode ode ); if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); testDocElem( testDocElem( searchResult); searchResult); return searchResult; searchResult; } else { prin print( t( "Can "Canno not t find find " + targ target et ); return return null; null; } } /* Crea Create te a func functi tion on to find find the the pare parent nt node node elem elemen ent t of the the targ target et * elemen ment */ */ function function testDoc testDocElem Elem( ( sourceO sourceObjec bject t ) { var docElement docElement = sourceObject.is sourceObject.isDocument DocumentElement( Element(); ); if ( docE docEle leme ment nt == true true ) { var nodeName nodeName = sourceO sourceObjec bject.g t.getNa etName() me(); ; prin print( t( "Suc "Succe cess ss. . The The elem elemen ent t " + node nodeNa Name me + " is the the DOM DOM docu docume ment nt element. element." " ); return valueFound; valueFound; } else { var nodeName nodeName = sourceO sourceObjec bject.g t.getNa etName() me(); ; prin print( t( "Fai "Fail. l. The The elem elemen ent t " + node nodeNa Name me + " is not not the the DOM DOM docu docume ment nt element. element." " ); valueFou valueFound nd = null; null; return valueFound; valueFound; } } /* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Target TargetNod Node. e. Run Run func functio tions ns. . print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "parent "parent1"; 1"; XMLSourc XMLSource e = XMLFile XMLFile; ; searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( searchResults, searchResults, TargetNode TargetNode );
*/
/* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Target TargetNod Node. e. Run Run func functio tions ns. . print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "docume "document"; nt"; XMLSourc XMLSource e = XMLFile XMLFile; ; searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( searchResults, searchResults, TargetNode TargetNode );
*/
XML.setAttributeValue(AttributeName XML.setAttributeValue( AttributeName , AttributeValue ) This method adds or updates updates the attribute attribute value of the target target attribute. attribute. Use the XML.getxxx XML.getxxx methods methods to navigate navigate through an XML document. This method method does not return any values. values.
100
The syntax is: setAttributeValue( AttributeName , AttributeValue ) AttributeValue ) The following arguments are valid for this method: at AttributeName
String String
The XML attrib attribute ute whose whose value value you you want the script script to add or update update..
AttributeValue
String String
Specif Specifies ies the text text stri string ng you you want want the script script to use use as as the the XML attribu attribute te value. value. Must Must cont contain ain characters valid for an XML element (for example, the string cannot include the characters < or >).
Example This example example adds or updates updates the attribute value value of any given element element in an XML document. It requires a local XML file, such as a file called C:\test.xml containing the following sample data: " />" /* Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. * Use Use XMLF XMLFil ile e to stor store e a vali valid d XML XML file file. . * The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */ var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test.xm t.xml", l", true true ); var XMLSour XMLSource; ce; var TargetNode; TargetNode; var TargetAttribute TargetAttribute; ; var TargetValue; TargetValue; var searchResults; searchResults; /* * * * * *
Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t conta contain ining ing the the eleme element nt. . This This func functi tion on assu assume mes s that that ther there e is only only one one inst instan ance ce of the the targ target et elem elemen ent t in the the sour source ce data data. . If it find finds s more more than than one one elem elemen ent t in the the data data, , it retur returns ns only only the firs first t inst instan ance ce of the the elem elemen ent. t. */
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else {
101
node node = childN childNod ode; e; } } return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function printFindResult printFindResults( s( target, searchResult, searchResult, attributeName, attributeName, attributeValue attributeValue ) { prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + targ target et ); if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); var attribut attributeSet eSet = setAttri setAttribute buteVal Value( ue( searchRe searchResult sult, , attribut attributeNam eName, e, attributeValue attributeValue ); prin print( t( "The "The XML XML obje object ct is " + sear search chRe Resu sult lt ); return attributeSet; attributeSet; } else { prin print( t( "Can "Canno not t find find " + targ target et ); return return null; null; } } /* Crea Create te a func functi tion on to set set the the attr attrib ibut ute e valu value e of the the targ target et * attr attrib ibut ute e */ function setAttributeValue( setAttributeValue( sourceObject, sourceObject, attributeName, attributeName, attributeValue attributeValue ) { print print( ( "Sett "Setting ing attri attribut bute e value value of " + attri attribu buteN teNam ame e ); var setAttributeVa setAttributeValue lue = sourceObject.se sourceObject.setAttrib tAttributeValue uteValue( ( attributeName, attributeName, attributeValue attributeValue ); var newAttributeVa newAttributeValue lue = sourceObject.ge sourceObject.getAttrib tAttributeValue uteValue( ( attributeName attributeName ); prin print( t( "The "The valu value e of " + attr attrib ibut uteN eNam ame e + " is now now " + newAttributeVal newAttributeValue ue ); return newAttributeVal newAttributeValue; ue; } /* Set Set vari variabl able e value values s for for XMLFi XMLFile le and Targe TargetNo tNode de. . Run Run func functio tions ns */ print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "child1 "child1"; "; XMLSourc XMLSource e = XMLFile XMLFile; ; TargetAttribute TargetAttribute = "attribute1"; "attribute1"; TargetVa TargetValue lue = "z"; searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( TargetNode, TargetNode, searchResults, searchResults, TargetAttribute, TargetAttribute, TargetValue TargetValue ); print print( ( "Pro "Proces cessi sing ng XML XML from from XMLFi XMLFile le... ... \n" ); TargetNo TargetNode de = "child2 "child2"; "; XMLSourc XMLSource e = XMLFile XMLFile; ; TargetAttribute TargetAttribute = "attribute1"; "attribute1"; TargetVa TargetValue lue = "z"; searchRe searchResul sults ts = findTarg findTargetEl etElemen ement( t( XMLSourc XMLSource, e, TargetN TargetNode ode ); printFindResult printFindResults( s( TargetNode, TargetNode, searchResults, searchResults, TargetAttribute, TargetAttribute, TargetValue TargetValue );
102
XML.setContent(String XML.setContent( String ) or XML.setContent XML.setContent(" ("FilePath 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 successfully parse parse the XML input. It always creates 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] XML] @nnnnnnnnnn @nnnnnnnnnn - ) is not valid XML. Use the toXMLString toXMLString method method to convert an XML object to an XML string. The syntax is: setContent( String ) Or setContent( "FilePath "FilePath", ", IsFile ) IsFile ) The following arguments are valid for this method: String
String String
Specif Specifies ies the text text stri string ng you you want want the script script to parse parse as on XML object object.. Must Must cont contain ain a vali valid d XML document with a document element.
FilePath
String String
Specif Specifies ies the path path to the XML docum document ent you want want the the scri script pt to parse parse an XML object object.. To indica indicate te 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 IsFile argument to true.
IsFile
Bool Boolea eann
Spec Specif ifie iess whet whethe herr the the String argument is a string or a file path. A true value indicates indicates the String argument is a file path. Any other value, including omitting omitting the second argument, indicates that the String argument is a text string.
Example This example example attempts to create an XML object from five different sources. sources. It requires the following following sample data:
A valid XML string, such as:
"" An XML string with more than one document element, such as:
"" A local XML file, such as a file called C:\test.xml containing the following sample data:
" />" 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
/* * * * * * * *
Creat Create e a func functio tion n to execu execute te the the setC setCont onten ent t metho method. d. The The func functi tion on creat creates es a new new XML XML obje object ct xmlO xmlObj bj. . It sets sets the the cont conten ent t of the XML obje object ct to the the sour source ce argum argumen ent. t. The The isFi isFile le argu argume ment nt dete determ rmin ines es if the the sour source ce is an XML stri string ng or file pa path. If setC setCon onte tent nt retu return rns s true true, , it prin prints ts an XML XML stri string ng and and retu return rns s the the XML obj object. ct. If setC setCon onte tent nt retu return rns s fals false, e, it prin prints ts the the sour source ce and and retu return rns s null null. . */
103
function function setXML( setXML( source, source, isFile isFile ) { var var xmlO xmlObj bj = new new XML( XML(); ); if ( xmlOb xmlObj. j.set setCo Conte ntent nt( ( sourc source, e, isFil isFile e ) ) { var xmlDoc xmlDoc = xmlObj.t xmlObj.toXM oXMLStr LString( ing(); ); print print( ( "setC "setCon onten tent t succe succeede eded! d! \n The XML docum documen ent t is: is: \n" \n" + xmlDo xmlDoc c ); return return xmlObj; xmlObj; } else { print print( ( "setC "setCon onten tent t faile failed. d. \n Coul Could d not not parse parse the the follo followi wing ng input input as XML: XML: \n" \n" + sour source ce ); return return null; null; } } /* * * * * * * *
Creat Create e varia variable bles s to store store your your XML sourc source e object objects. s. Use Use xmlO xmlObj bjec ect t to test test sett settin ing g cont conten ent t to an XML XML obje object ct. . xmlOb xmlObje jectC ctCon onver verte ted d conve convert rts s xmlO xmlObje bject ct to an XML XML strin string. g. Note: Note: The The toXML toXMLst strin ring g metho method d remov removes es the objec object t heade header r infor informat matio ion. n. Use Use xmlS xmlStr trin ing g to test test sett settin ing g cont conten ent t to an XML XML stri string ng. . Note Note: : You You must must use use the the back backsl slas ash h char charac acte ter r to esca escape pe out out quot quotat atio ion n mark marks s in your your XML XML stri string ng. . Use Use xmlF xmlFil ile e to test test sett settin ing g cont conten ent t to an XML file file. . */
var xmlString xmlString = ""; />"; var xmlBad = "< />"; var xmlFile xmlFile = "C:\\te "C:\\test.x st.xml"; ml"; var xmlObje xmlObject ct = system.u system.users sers; ; var xmlObjectConver xmlObjectConverted ted = xmlObject.toXML xmlObject.toXMLString() String(); ;
/* Note Note: : You You can can omit omit the the isFi isFile le argu argume ment nt when when the the cont conten ent t sour source ce is * an XML XML str string. * See See the the xmlS xmlStr trin ing g exam exampl ple e belo below. w. */ print print( ( "Tes "Testin ting g setti setting ng conte content nt to a valid valid XML XML strin string. g...\ ..\n" n" ); setXML( setXML( xmlStri xmlString ng ); print print( ( "Tes "Testin ting g setti setting ng conte content nt to an XML XML strin string g with with more more than than one document document element element...\ ...\n" n" ); print print( ( "The "The nonnon-com compl plian iant t XML XML strin string g befor before e conve conversi rsion on is: is: \n" + xmlBa xmlBad d ); setXML( setXML( xmlBad xmlBad ); print print( ( "Tes "Testin ting g setti setting ng conte content nt to an XML XML file. file... ..\n" \n" ); setXM setXML( L( xmlFi xmlFile le, , true true ); print print( ( "Tes "Testin ting g setti setting ng conte content nt to an exist existin ing g XML XML objec object. t...\ ..\n" n" ); setXML( setXML( xmlObje xmlObject, ct, false false ); print print( ( "Tes "Testin ting g setti setting ng conte content nt to an exist existin ing g XML XML objec object t conve converte rted d to an XML string. string...\n ..\n" " ); setXML( setXML( xmlObje xmlObjectCo ctConver nverted ted, , false false );
XML.setNodeValue(String XML.setNodeValue( String ) This method method is used to add or update the value of the current element. 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. element. Use the the XML.get XML.getxxx xxx methods methods to navigate through an XML document.
104
The syntax is: setNodeValue( String ) The following argument is valid for this method:
String
String String
Specif Specifies ies the text text stri string ng you you want want the script script to add as the XML eleme element nt value. value. Must Must cont contain ain characters valid for XML (for example, the string cannot include the characters < or > except as XML entities such as < and >).
Example This example example sets the value of the elements elements in an XML document. document. It requires a local XML file, such as C:\test03.xml containing: "" cument>" /* * * * *
Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. Use Use XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . Use Use sour source ceXM XMLS LStr trin ing g to stor store e a vali valid d XML XML stri string ng. . The The scri script pt sets sets the the conte content nt of XMLStr XMLString ing to sourc sourceX eXMLS MLStr tring ing. . The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */
var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test03. t03.xml xml", ", true ); var TargetNode; TargetNode; var TargetValue; TargetValue; var findElement; findElement; /* * * * * *
Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t conta contain ining ing the the eleme element nt. . This This func functi tion on assu assume mes s that that ther there e is only only one one inst instan ance ce of the the targ target et elem elemen ent t in the the sour source ce data data. . If it find finds s more more than than one one elem elemen ent t in the the data data it only only retu return rns s the the firs first t inst instan ance ce of the the elem elemen ent. t. */
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; }
105
} return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function function setElem setElementV entValue alue( ( searchR searchResul esult, t, targetNo targetNode, de, newValu newValue e ) { prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + targ target etNo Node de ); if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); searchResult.se searchResult.setNodeVal tNodeValue( ue( newValue newValue ); prin print( t("T "The he new new valu value e of " + targ target etNo Node de + " is: is: " + sear search chRe Resu sult lt); ); return searchResult; searchResult; } else { print print( ( "Cann "Cannot ot find find " + targe targetNo tNode de ); return return null; null; } } TargetNo TargetNode de = "parent "parent1"; 1"; TargetVa TargetValue lue = "1234"; "1234"; findElem findElement ent = findTar findTargetE getEleme lement( nt( XMLFile XMLFile, , TargetN TargetNode ode ); setElementValue setElementValue( ( findElement, findElement, TargetNode, TargetNode, TargetValue TargetValue );
XML.setText(String XML.setText(String ) This method, which is a synonym for setNodeValue(), is used to add or update the value of the current element. element. It returns an XML object containing containing the new value of the current current element; element; or returns returns null if the method method cannot set a value for the element. element. Use the XML.get XML.getxxx xxx methods methods to navigate through an XML document. The syntax is: setText( String ) The following argument is valid for this method: at String
String String
Specif Specifies ies the text text string string you you want want the the metho method d to to add as the XML eleme element nt value. value. Must Must contain characters valid for XML (for example, the string cannot include the characters < or > except as XML entities such as < and >).
Example This example example sets the value of the elements elements in an XML document. document. It requires a local XML file, such as C:\test03.xml containing "" cument>" /* * * * *
Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. Use Use XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . Use Use sour source ceXM XMLS LStr trin ing g to stor store e a vali valid d XML XML stri string ng. . The The scri script pt sets sets the the conte content nt of XMLStr XMLString ing to sourc sourceX eXMLS MLStr tring ing. . The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */
var XMLFil XMLFile e = new new XML() XML(); ;
106
XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test03. t03.xml xml", ", true ); var TargetNode; TargetNode; var TargetValue; TargetValue; var findElement; findElement; /* * * * * *
Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t conta contain ining ing the the eleme element nt. . This This func functi tion on assu assume mes s that that ther there e is only only one one inst instan ance ce of the the targ target et elem elemen ent t in the the sour source ce data data. . If it find finds s more more than than one one elem elemen ent t in the the data data it only only retu return rns s the the firs first t inst instan ance ce of the the elem elemen ent. t. */
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null; } childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; } } return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function function setElem setElementV entValue alue( ( searchR searchResul esult, t, targetNo targetNode, de, newValu newValue e ) { prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + targ target etNo Node de ); if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); searchResult.se searchResult.setText( tText( newValue newValue ); prin print( t("T "The he new new valu value e of " + targ target etNo Node de + " is: is: " + sear search chRe Resu sult lt); ); return searchResult; searchResult; } else { print print( ( "Cann "Cannot ot find find " + targe targetNo tNode de ); return return null; null; } } TargetNo TargetNode de = "parent "parent1"; 1"; TargetVa TargetValue lue = "1234"; "1234";
XML.setValue(String XML.setValue(String ) This method, which is a synonym for setNodeValue(), is used to add or update the value of the current element. element. It returns an XML object containing containing the new value of the current current element; element; or returns returns null if the method method cannot set a value for the element. element. Use the XML.get XML.getxxx xxx methods methods to navigate through an XML document. The syntax is: setValue( String ) The following argument is valid for this method: at String
String String
Specif Specifies ies the text text string string you you want want the the metho method d to to add as the XML eleme element nt value. value. Must Must contain characters valid for XML (for example, the string cannot include the characters < or > except as XML entities such as < and >).
Example This example example sets the value of the elements elements in an XML document. document. It requires as sample sample data a local XML file, such as a file called C:\test03.xml containing: "" cument>" /* * * * *
Creat Create e varia variable bles s to store store XML objec objects ts and and string strings. s. Use Use XMLO XMLObj bjec ect t to store store a vali valid d XML XML obje object ct such such as an XML XML file file. . Use Use sour source ceXM XMLS LStr trin ing g to stor store e a vali valid d XML XML stri string ng. . The The scri script pt sets sets the the conte content nt of XMLStr XMLString ing to sourc sourceX eXMLS MLStr tring ing. . The The scri script pt assi assign gns s valu values es to the the empt empty y vari variab able les s late later r on */
var XMLFil XMLFile e = new new XML() XML(); ; XMLFile XMLFile = XMLFile. XMLFile.set setCont Content( ent( "C:\\tes "C:\\test03. t03.xml xml", ", true ); var TargetNode; TargetNode; var TargetValue; TargetValue; var findElement; findElement; /* * * * * *
Crea Create te a func functi tion on that that sear search ches es an XML XML obje object ct (nod (node) e) for for a parti particu cular lar elemen element t (targ (target etEle Elem) m) and return returns s an XML XML objec object t conta contain ining ing the the eleme element nt. . This This func functi tion on assu assume mes s that that ther there e is only only one one inst instan ance ce of the the targ target et elem elemen ent t in the the sour source ce data data. . If it find finds s more more than than one one elem elemen ent t in the the data data it only only retu return rns s the the firs first t inst instan ance ce of the the elem elemen ent. t. */
function function findTar findTargetE getEleme lement( nt( node, node, targetEl targetElem em ) { while while (node (node != null null && node node.ge .getN tNode odeNa Name( me() ) != targe targetEl tElem em ) { var childNode childNode = node.getFirstCh node.getFirstChildElem ildElement(); ent(); if (chil (childN dNode ode == null) null) { childNode childNode = node.getNextSi node.getNextSiblingEle blingElement(); ment(); while while (childNo (childNode de == null) null) { node = node.getParentN node.getParentNode(); ode(); if ( node == nul null ) { return return null; null;
108
} childNode childNode = node.getNextSib node.getNextSiblingElem lingElement(); ent(); } node node = childN childNod ode; e; } else { node node = childN childNod ode; e; } } return return node; node; } /* Crea Create te a func functi tion on to prin print t the the targ target et elem elemen ent t and and sear search ch resu result lts s */ function function setElem setElementV entValue alue( ( searchR searchResul esult, t, targetNo targetNode, de, newValu newValue e ) { prin print( t( "The "The targ target et elem elemen ent t we are are look lookin ing g for for is: is: " + targ target etNo Node de ); if ( sear search chRe Resu sult lt != null null ) { var elementName elementName = searchResult.ge searchResult.getNodeNam tNodeName(); e(); prin print( t( "Fou "Found nd elem elemen ent t " + elem elemen entN tNam ame e + " in: in: \n" \n" + sear search chRe Resu sult lt + "\n" "\n" ); searchResult.se searchResult.setValue( tValue( newValue ); prin print( t( "The "The new new valu value e of " + targ target etNo Node de + " is: is: " + sear search chRe Resu sult lt ); return searchResult; searchResult; } else { print print( ( "Cann "Cannot ot find find " + targe targetNo tNode de ); return return null; null; } } TargetNo TargetNode de = "parent "parent1"; 1"; TargetVa TargetValue lue = "1234"; "1234"; findElem findElement ent = findTar findTargetE getEleme lement( nt( XMLFile XMLFile, , TargetN TargetNode ode ); setElementValue setElementValue( ( findElement, findElement, TargetNode, TargetNode, TargetValue 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. object. Use the the XML.get XML.getxxx xxx methods methods to navigate through an XML document. The syntax for use is: toXMLString() No arguments are passed. Example This example example converts converts an XML object into a valid XML document. document. It requires requires as sample data an existing XML object, such as the list of currently logged on users stored in system.users. var xmlObje xmlObject ct = print print( ( "Thi "This s is var xmlStri xmlString ng = print print( ( "Thi "This s is xmlStrin xmlString g );
system.u system.users sers; ; the origi original nal XML objec object: t:\n" \n" + xmlOb xmlObje ject ct ); xmlObjec xmlObject.to t.toXMLS XMLStri tring() ng(); ; the XML objec object t afte after r conve convers rsion ion to a strin string:\ g:\n" n" +
109
JavaScript methods for the XMLDate object XMLDate.addDuration(duration 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: at duration
ISO 8601 duration string
Yes
Contai Contains ns the ISO 8601 8601 durati duration on string string or variab variable le value value you want 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( print( "Creati "Creating ng XMLDate XMLDate var var d = new new XMLD XMLDat ate( e( new new prin print( t( "The "The valu value e of the the prin print( t( "Add "Addin ing g 1 year year, , 2 var dur dur = d.add d.addDur Durat ation ion( ( prin print( t( "The "The valu value e of the the
object.. object..." ." ); Date Date() () ); new new XMLD XMLDat ate e obje object ct is: is: " + d ); mont months hs, , 3 days days, , and and 4 hour hours s to date date.. ..." ." ); "P1Y2 "P1Y2M3D M3DT4 T4H" H" ); new new XMLD XMLDat ate e obje object ct is: is: " + dur dur );
XMLDate.getDate() This method method returns a JavaScript JavaScript date/time date/time object as a string; string; or null if the conversion 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( print( "Creati "Creating ng XMLDate XMLDate object.. object..." ." ); var var d = new new XMLD XMLDat ate( e( new new Date Date() () ); prin print( t( "The "The valu value e of the the new new XMLD XMLDat ate e obje object ct is: is: " + d ); print print( ( "Con "Conver verti ting ng the the XMLDa XMLDate te to a Java JavaScr Scrip ipt t objec object. t..." .." ); var js = d.get d.getDa Date( te(); ); print print( ( "The "The Java JavaScr Scrip ipt t date/ date/ti time me objec object t is: " + js );
XMLDate.getDatum() The method returns a Service Manager-formatted date/time Datum object in a string; or returns null if the conversion fails. The syntax is: getDatum() No arguments are passed.
110
Example This example creates a new XMLDate object containing today's date; converts the XMLDate object to Service Manager-formatted date/time Datum object; and then displays the result. print( print( "Creati "Creating ng XMLDate XMLDate object.. object..." ." ); var var d = new new XMLD XMLDat ate( e( new new Date Date() () ); prin print( t( "The "The valu value e of the the new new XMLD XMLDat ate e obje object ct is: is: " + d ); print print( ( "Con "Conver verti ting ng the the XMLDa XMLDate te to a Serv Service ice Manag Manager er Datum Datum.. ..." ." ); var sm = d.get d.getDa Datum tum() (); ; prin print( t( "The "The Serv Servic ice e Mana Manage ger r Datu Datum m obje object ct is: is: " + sm );
XMLDate.getGMTSCDateTimeString() The method returns a Service Manager-formatted date/time string; or returns null if the conversion fails. fails. The syntax syntax is: getSCDateTimeString() No arguments are passed. Example This example creates a new XMLDate object containing today's date; converts the XMLDate object to Service Manager-formatted date/time string; and then displays the result. print( print( "Creati "Creating ng XMLDate XMLDate object.. object..." ." ); var var d = new new XMLD XMLDat ate( e( new new Date Date() () ); prin print( t( "The "The valu value e of the the new new XMLD XMLDat ate e obje object ct is: is: " + d ); print("C print("Conv onverti erting ng the XMLDate XMLDate to a Service Service Manager Manager date/ti date/time me string. string...") .."); ; var sm = d.getGM d.getGMTSCD TSCDateT ateTimeS imeStrin tring() g(); ; prin print( t( "The "The Serv Servic ice e Mana Manage ger r GMT GMT date date/t /tim ime e stri string ng is: is: " + sm );
XMLDate.getISODate() The getISODate() method returns a string containing the date portion of a date/time object in ISO format; format; or returns null if the conversion conversion fails. The syntax 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( print( "Creati "Creating ng XMLDate XMLDate object.. object..." ." ); var var d = new new XMLD XMLDat ate( e( new new Date Date() () ); prin print( t( "The "The valu value e of the the new new XMLD XMLDat ate e obje object ct is: is: " + d ); print print( ( "Con "Conver verti ting ng the the XMLDa XMLDate te to ISO forma format. t..." .." ); var ISO = d.getISO d.getISODat Date(); e(); prin print( t( "The "The ISO ISO date date is: is: " + ISO ISO );
XMLDate.getISODateTimeString() This method returns a string containing the date and time portion of date/time object in ISO format; or returns null null if the conversion conversion fails. The syntax syntax is: getISODateTimeString() No arguments are passed.
111
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( print( "Creati "Creating ng XMLDate XMLDate object.. object..." ." ); var var d = new new XMLD XMLDat ate( e( new new Date Date() () ); prin print( t( "The "The valu value e of the the new new XMLD XMLDat ate e obje object ct is: is: " + d ); print print( ( "Con "Conver verti ting ng the the XMLDa XMLDate te to ISO forma format. t..." .." ); var ISO = d.getISO d.getISODat DateTim eTimeStr eString( ing(); ); prin print( t( "The "The ISO ISO date date and and time time is: is: " + ISO 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 conversion fails. The syntax 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( print( "Creati "Creating ng XMLDate XMLDate object.. object..." ." ); var var d = new new XMLD XMLDat ate( e( new new Date Date() () ); prin print( t( "The "The valu value e of the the new new XMLD XMLDat ate e obje object ct is: is: " + d ); print print( ( "Con "Conver verti ting ng the the XMLDa XMLDate te to ISO forma format. t..." .." ); var ISO ISO = d.get d.getISO ISODa Day() y(); ; prin print( t( "The "The ISO ISO day day is: is: " + ISO 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 conversion fails. The syntax syntax is: 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( print( "Creati "Creating ng XMLDate XMLDate object.. object..." ." ); var var d = new new XMLD XMLDat ate( e( new new Date Date() () ); prin print( t( "The "The valu value e of the the new new XMLD XMLDat ate e obje object ct is: is: " + d ); print print( ( "Con "Conver verti ting ng the the XMLDa XMLDate te to ISO forma format. t..." .." ); var ISO = d.getISO d.getISOMon Month() th(); ; prin print( t( "The "The ISO ISO mont month h is: is: " + ISO 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 conversion fails. The syntax syntax is: getISOTime() No arguments are passed.
112
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( print( "Creati "Creating ng XMLDate XMLDate object.. object..." ." ); var var d = new new XMLD XMLDat ate( e( new new Date Date() () ); prin print( t( "The "The valu value e of the the new new XMLD XMLDat ate e obje object ct is: is: " + d ); print print( ( "Con "Conver verti ting ng the the XMLDa XMLDate te to ISO forma format. t..." .." ); var ISO = d.getISO d.getISOTim Time(); e(); prin print( t( "The "The ISO ISO time time is: is: " + ISO 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 conversion fails. The syntax 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( print( "Creati "Creating ng XMLDate XMLDate object.. object..." ." ); var var d = new new XMLD XMLDat ate( e( new new Date Date() () ); prin print( t( "The "The valu value e of the the new new XMLD XMLDat ate e obje object ct is: is: " + d ); print print( ( "Con "Conver verti ting ng the the XMLDa XMLDate te to ISO forma format. t..." .." ); var ISO = d.getISO d.getISOYea Year(); r(); prin print( t( "The "The ISO ISO year year is: is: " + ISO ISO );
XMLDate.getSCDateTimeString() This method returns a Service Manager-formatted date/time string; or returns null if the conversion fails. fails. The syntax syntax is: getSCDateTimeString() No arguments are passed. Example This example creates a new XMLDate object containing today's date; converts the XMLDate object to Service Manager-formatted date/time string; and then displays the result. print( print( "Creati "Creating ng XMLDate XMLDate object.. object..." ." ); var var d = new new XMLD XMLDat ate( e( new new Date Date() () ); prin print( t( "The "The valu value e of the the new new XMLD XMLDat ate e obje object ct is: is: " + d ); print("C print("Conv onverti erting ng the XMLDate XMLDate to a Service Service Manager Manager date/ti date/time me string. string...") .."); ; var sm = d.getSC d.getSCDate DateTime TimeStri String() ng(); ; prin print( t( "The "The Serv Servic ice e Mana Manage ger r date date/t /tim ime e stri string ng is: is: " + sm );
XMLDate.JSDate() This method, which is an alias of the getDate() method, returns a JavaScript date/time object; or returns returns null if the conversion conversion fails. The syntax syntax is: JSDate() No arguments are passed.
113
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( print( "Creati "Creating ng XMLDate XMLDate object.. object..." ." ); var var d = new new XMLD XMLDat ate( e( new new Date Date() () ); prin print( t( "The "The valu value e of the the new new XMLD XMLDat ate e obje object ct is: is: " + d ); print print( ( "Con "Conver verti ting ng the the XMLDa XMLDate te to a Java JavaScr Scrip ipt t objec object. t..." .." ); var js = d.JSD d.JSDat ate() e(); ; print print( ( "The "The Java JavaScr Scrip ipt t date/ date/ti time me objec object t is: " + js );
XMLDate.toSCDuration(duration XMLDate.toSCDuration( duration ) This method returns a string containing the new Service Manager 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: at duration
ISO 8601 duration string
Yes
Contai Contains ns the ISO 8601 8601 durati duration on string string or variab variable le value value you want want the method to convert to a Service Manager duration.
Example This example creates a new XMLDate object containing a hard-coded ISO date; converts the ISO date/time to a Service Manager duration; and displays the result. print( print( "Creati "Creating ng XMLDate XMLDate object.. object..." ." ); var d = new new XMLD XMLDate ate( ( "P01DT "P01DT12 12H01 H01M0 M01S" 1S" ); prin print( t( "The "The valu value e of the the new new XMLD XMLDat ate e obje object ct is: is: " + d ); prin print( t( "Con "Conve vert rtin ing g " + d.to d.toSt Stri ring ng() () + " to a SC dura durati tion on.. ..." ." ); var smDur smDur = d.toSCD d.toSCDurat uration( ion(); ); print print( ( "The "The Serv Service ice Manag Manager er durat duratio ion n is: is: " + smDur smDur );
114
Cross-refer Cross -reference: ence: Index of methods methods and functions functions by task task Array handling Service Manager arrays are held in SCFile objects. They have to be converted to a JavaScript array by using the toArray() toArray() method. method. As an example, example, the following following code shows shows how to check and fill an array: CI=new SCFile("device" SCFile("device") ) var array array _incid inciden ents ts = new Array Array(); (); v ar i nd = 0 ; while(CI.array _inciden incidents[i ts[ind] nd] != null) null) { array _incidents[ind]=CI.array _incidents[ind]; ind++; } /* ********************************************************************** The follo followi wing ng state stateme ment nt achie achieves ves the the same same resul results ts as the above above while whileloop: array _incidents=CI.array _incidents.toArray() ********************************************************************** */ var var j=0; j=0; /* ********************************************************************** Since Since index indexOf Of is not not availa availabl ble e on Array Arrays, s, the the array array has has to be conve converte rted d to a stri string ng befo before re usin using g this this func functi tion on to find find if a sing single le elem elemen ent t is part part of the the arra array. y. ********************************************************************** */ var var temp temp _strin string g = arra array y _incidents.toString(); var i = tem temp _string.indexOf(incNumber); /* ********************************************************************** the the next next set set of stat statem emen ents ts can can be repl replac aced ed by the the push push() () meth method od. . The The line lines s of code code woul would d be as foll follow ows: s: if (i<0) (i<0) { var newArray newArrayLen Length gth = array array _incidents.push( incidents.push( incNumber ); ********************************************************************** */ if (i < 0) { if (arra (array y _inciden incidents ts == null) null) { j=0; } else { j=array _incidents.length; } array _inciden incidents[j ts[j] ] = incNumbe incNumber; r; }
115
SCFile
32
Create Createss a SCFile SCFile object object contai containin ning g the provid provided ed record record,, struct structur ure, e, or array. array.
SCFile.getSize()
47
Retu Return rnss the the numb number er of arra arrayy elem elemen ents ts in an arra array. y.
SCFile.join()
50
Retur Returns ns the eleme elements nts of either either a Servic Servicee Manage Managerr Datum Datum array array object object or a JavaScript array as a string.
SCFile.length()
52
Retu Return rnss the the numb number er of arra arrayy elem elemen ents ts in an arra array. y.
SCFile.pop()
54
Remove Removess the last last eleme element nt from from a JavaS JavaScri cript pt array array and retur returns ns the eleme element nt removed as a string.
SCFile.push()
55
Adds Adds an entry entry to the end of a JavaSc JavaScrip riptt array array and return returnss the total total numbe numberr of entries in the array.
SCFile.shift()
56
Remove Removess the first first elemen elementt from from a JavaSc JavaScrip riptt array array and retur returns ns the eleme element nt removed as a string.
SCFile.toArray()
57
Conver Converts ts a Servic Servicee Manage Managerr Datum Datum object object into into a JavaSc JavaScrip riptt array. array.
SCFile.unshift()
58
Adds Adds an entry entry to the beginn beginning ing of a JavaScr JavaScript ipt array array and retur returns ns the total total number of entries in the array.
Date/Time handling XMLDate
35
Create Createss or conver converts ts to an XML Date Date object object..
SCFile.JSDate()
51
Conver Converted ted Servi Service ce Manage Managerr date/ti date/time me data data into into JavaSc JavaScrip riptt date/time objects (SCFile now automatically converts Service Manager date/time data into JavaScript date/time objects).
XMLDate.addDuration()
110
Returns Returns an XMLDate XMLDate object containing containing the new date/time date/time after adding the duration from the duration argument.
XMLDate.getDate()
110 110
Retur Returns ns a JavaScr JavaScript ipt date/t date/time ime object object as a stri string. ng.
XMLDate.getDatum()
110
Returns Returns a Servic Servicee Manage Manager-for r-formatte matted d date/time date/time Datum object object in a string.
XMLDate.getGMTSCDateTimeString()
111
Returns Returns a Service Service Manager-for Manager-formatte matted d date/time date/time string. string.
XMLDate.getISODate()
111
Returns Returns a string string containing containing the date portion portion of a date/t date/time ime object object in ISO format.
XMLDate.getISODateTimeString()
111
Returns Returns a string string containing containing the date and time portion portion of date/time date/time object in ISO format.
XMLDate.getISODay()
112
Returns Returns a string string containing containing the day portion portion of date/time date/time object object in in ISO format.
XMLDate.getISOMonth()
112
Returns Returns a string string containing containing the month month portio portionn of of d date/ti ate/time me object object in ISO format.
XMLDate.getISOTime()
112
Returns Returns a string string containing containing the time portion portion of date/time date/time object object in ISO format.
XMLDate.getISOYear()
113
Returns Returns a string string containing containing the year portion portion of date/time date/time object object in ISO format.
XMLDate.getSCDateTimeString()
113
Returns Returns a Service Service Manager-for Manager-formatte matted d date/time date/time string. string.
XMLDate.JSDate()
113 113
Retur Returns ns a JavaScr JavaScript ipt date/t date/time ime object object..
XMLDate.toSCDuration()
114
Returns Returns a string string containing containing the new Service Service Manager Manager duration duration converted from an ISO 8601 duration.
116
Database or file manipulation SCFile
32
Creat Creates es an SCFi SCFile le obje object ct cont contain ainin ing g the the prov provid ided ed reco record rd,, stru struct ctur ure, e, or arra array. y.
SCFile.doInsert()
39
Create ates a Service Manager recor cord.
SCFile.doDelete()
38
Remo Remove vess a Serv Servic icee Mana Manage gerr reco record rd (ali (alias as of SCFi SCFile le.d .doR oRem emov ove) e)..
SCFile.doRemove()
40
Removes a Service Manage ager record.
SCFile.doSave()
40
Adds Adds to or upda update tess the the Serv Servic icee Mana Manage gerr data databa base se..
SCFile.doSelect()
41
Runs Runs the the spec specif ifie ied d quer queryy and retu return rnss a list list of reco record rdss match matchin ing g the quer query. y...
SCFile.doUpdate()
42
Updates tes a Service Mana anager record.
SCFile.getFirst()
43
Retu Return rnss the the first irst rec record ord in a recor ecord d list. ist.
SCFile.getLast()
44
Retu Return rnss the the last record cord in a reco recorrd list. ist.
SCFile.getNext()
45
Retu Return rnss the the next ext reco recorrd in a recor ecord d lis list.
SCFile.getPrev()
46
Retu Return rnss the the prev previo ious us reco record rd in a reco record rd list. ist.
SCFile.isRecord()
Error! Bookmar k not defined.
Verifies that the query or query condition returns a Service Manager record.
SCFile.setValue()
56
Adds Adds or upda update tess a Serv Servic icee Mana Manage gerr reco record rd with with the the new new fiel field d valu valuee defin defined ed in the the newValue argument.
system.oldrecord
20
Call Callss the the last last Serv Servic icee Mana Manage gerr reco record rd into into memor emory. y.
system.record
20
Call Callss the the curr curren entt Serv Servic icee Mana Manage gerr reco record rd into into memo memory ry..
writeFile
23
Writ Writes es the the cont conten ents ts of the the obje object ct para parame meter ter to the the file file spec specif ifie ied d in the the path path parameter.
readFile
23
Read Readss the cont conten ents ts of a loca locall file file and and retu return rnss a stri string ng obje object ct with with the the cont conten ents ts of that file.
Basic functionality system.files
18
Calls Calls a partic particula ularr Servi Service ce Manage Managerr table table into into memo memory. ry.
system.forms
18
Calls Calls a partic particula ularr Servi Service ce Manage Managerr form form into into memory memory..
system.functions
19
Calls Calls a particular particular Service Service Manager Manager RAD function function from JavaScript JavaScript..
system.library
19
Calls Calls a part particu icular lar Servi Service ce Manage Managerr script script librar libraryy functi function. on.
system.oldrecord
20
Calls Calls the last last Servic Servicee Manage Managerr record record into into memor memory. y.
system.record
20
Calls Calls the curren currentt Servi Service ce Manage Managerr record record into into memory memory..
system.sysinfo
20
Calls Calls an XML list list of proper propertie tiess abo about ut the Servi Service ce Manage Managerr serv server er..
system.threads
21
Calls Calls an XML list list of the curren currentt Serv Service ice Manage Managerr thre threads ads into into memo memory. ry.
system.user
21
Calls Calls an XML list of propertie propertiess of of the the curren currently tly logged logged on Service Service Manager Manager user. user.
117
system.users
22
Calls Calls an XML list of the currently currently logged logged on Service Service Manager Manager users users into into memory. memory.
system.vars
22
Calls Calls a partic particula ularr Servi Service ce Manage Managerr variab variable le into into memor memory. y.
Query Operators
12
Operat Operators ors used used in query query expres expressi sions ons..
JavaScript return code properties
12
Intege Integerr valu values es to test test the the value valuess retu returne rned d by the metho methods ds of object objects. s.
print
22
Displays Displays the contents contents of the method method argument argument in the client client Messag Messages es view and also prints it in the Service Manager log file.
Quit
24
Stops the processin processing g of of JavaSc JavaScript ript from the point it is is called called and retur returns ns a failure failure return return code.
doHTTPRequest
26
Sends Sends an HTTP HTTP requ request est to a rem remote ote server server specif specifie ied d by by a URL. URL.
doSOAPRequest
26
Issues Issues a SOAP SOAP request request to to a remote remote server server specified specified by an URL and retur returns ns the SOAP response in a string or an error message.
help
29
Displays Displays a brief descriptio descriptionn of a Service Service Manager-de Manager-defined fined JavaScript JavaScript object. object.
RCtoString
29
Converts Converts a Service Service Manager Manager global global return return code value value into a localized localized text string. string.
execute
30
Vali Validat dates es the the synt syntax ax of a Java JavaSc Scri ript pt..
compile
30
Valida Validates tes the syntax syntax of a JavaSc JavaScri ript pt (alias (alias of execut execute) e)..
Attachment
31
Contai Contains ns attachm attachment ent data for use use with with doSOAP doSOAPReq Reque uest st method methods. s.
Header
32
Creat Creates es a (HTT (HTTP) P) Head Header er obje object. ct.
Conversions base64Encode
24
Conv Conver erts ts bina binary ry data data to a base base-6 -64 4 stri string ng form format at..
base64Decode
25
Conv Conver erts ts base base-6 -64 4 stri string ng data data to its its orig origin inal al form format at..
xmlstring
25
Conv Conver erts ts a Java JavaSc Scri ript pt stri string ng to an XML-f XML-for orma matttted ed stri string ng..
SCFile.JSDate()
51
Conv Conver erte ted d Serv Service ice Manag Manager er date/ date/titime me data data into into Java JavaSc Scri ript pt date date/t /tim imee obje object ctss (SCFile now automatically converts Service Manager date/time data into JavaScript date/time objects).
SCFile.setType()
Error! Bookmar k not defined.
Set the data type of Service Manager datum objects (SCFile now automatically converts Service Manager data types into JavaScript data types).
SCFile.toArray()
57
Conv Conver erts ts a Serv Servic icee Mana Manage gerr Datu Datum m obje object ct into into a Java JavaSc Scri ript pt arra array. y.
XML.toXMLString()
109 109
Conv Conver erts ts an XML XML objec bjectt into into a vali valid d XML XML stri string ng..
XML system.sysinfo
20
Calls Calls an XML list list of proper propertie tiess about about the Servi Service ce Manage Managerr server server..
system.threads
21
Calls Calls an XML list list of the curren currentt Serv Service ice Manage Managerr thread threadss into into memory memory..
118
system.user
21
Calls Calls an XML list list of proper propertie tiess of of the the curren currently tly logged logged on Servi Service ce Manage Managerr user.
system.users
22
Calls Calls an XML list list of the curren currently tly logge logged d on on Serv Service ice Manage Managerr user userss into into memory.
xmlstring
25
Conver Converts ts a JavaSc JavaScrip riptt string string to an XML-fo XML-forma rmatte tted d string string..
XML
34
Create Createss an empty empty XML object object where where you can store store and manipu manipulat latee XML XML documents.
XMLDate
35
Crea Create tess or conv conver erts ts to an XML XML Date Date obje object. ct.
SCFile.getXML()
50
Retur Returns ns an XML object object repre represen sentat tatio ionn of of the curren currentt SCFi SCFile le object. object.
XML.addAttribute()
59
Insert Insertss an attribu attribute te and attrib attribute ute value value into into the curren currentt eleme element. nt.
XML.addElement()
61
Insert Insertss an XML eleme element nt as a child child of the curren currentt eleme element. nt.
XML.appendNode()
63
Inse Insert rtss an XML XML node node into into an XML XML obje object. ct.
XML.createNode()
64
Crea Create tess an XML XML node node from from an XML XML obje object ct .
XML.getAttributeNode()
65
Retur Returns ns an an XML XML object object contai containin ning g the the targe targett attri attribut butee the the curren currentt elem element ent..
XML.getAttributeValue()
67
Retur Returns ns the string string value value of the targe targett attribu attribute. te.
XML.getDocumentElement()
69
Search Searches es an XML object object for the DOM DOM docu documen mentt elemen elementt (or (or "root" "root" node) node)..
XML.getFirstAttribute()
70
Retur Returns ns an object object repres represent enting ing the first first attribu attribute te of the curren currentt node node..
XML.getFirstChildElement()
73
Retur Returns ns an object object repres represent enting ing the first first child child node node of the curren currentt node node..
XML.getName()
75
Retur Returns ns a string string repre represen sentin ting g the name name of the curren currentt eleme element. nt.
XML.getNextAttribute()
76
Retur Returns ns an object object repres represent enting ing the first first attribu attribute te of the curren currentt node node..
XML.getNextSiblingElement()
79
Retur Returns ns an an obje object ct repres represent enting ing the next next node node at the the same same leve levell in in the the DOM tree as the current node.
XML.getNodeName()
82
Retur Returns ns a string string repre represen sentin ting g the the name name of of the the curre current nt ele elemen mentt or or attr attribu ibute. te.
XML.getNodeType()
83
Evalu Evaluate atess an XML object object and return returnss an an intege integerr repr represe esenti nting ng the XML DOM type of the current element or attribute.
XML.getNodeValue()
84
Retur Returns ns a string string repre represen sentin ting g the value value of the curren currentt XML XML elemen element. t.
XML.getParentNode()
86
Retur Returns ns an XML object object repre represen sentin ting g the parent parent node node of the curren currentt node node..
XML.getPrefix()
89
Retur Returns ns a stri string ng repre represen sentin ting g the namesp namespace ace value value of the curren currentt node node (element or attribute).
XML.getQualifiedName()
91
Retur Returns ns a string string repre represen sentin ting g the the name name of of the the curre current nt ele elemen mentt or or attr attribu ibute. te.
XML.getText()
93
Retur Returns ns a string string repre represen sentin ting g the the value value of the curren currentt XML XML elemen elementt (ali (alias as for getNodeValue).
XML.getValue()
95
Retur Returns ns a string string repre represen sentin ting g the the value value of the curren currentt XML XML elemen elementt (ali (alias as for getNodeValue).
XML.importNode()
97
Retur Returns ns an XML object object contai containin ning g a copy copy of the source source XML node. node.
XML.isDocumentElement()
99
Retur Returns ns the the Bool Boolean ean value value of true true ifif the the curren currentt elem element ent is the DOM docum document ent element (the "root" node of the XML document) or false if it is not.
XML.setAttributeValue()
100
Adds Adds or or upda updates tes the attribu attribute te value value of the target target attribu attribute. te.
XML.setContent()
103
Creates Creates an XML XML object object from a string string or the the contents contents of an extern external al file file object object
119
if it was able to successfully parse the XML input.
XML.setNodeValue()
104
Adds Adds or updat updates es the value value of the curre current nt elemen element. t.
XML.setText()
106
Adds or updates updates the value value of the current current element element (alias (alias for for setNodeValu setNodeValue). e).
XML.setValue()
108
Adds or updates updates the value value of the current current element element (alias (alias for for setNodeValu setNodeValue). e).
XML.toXMLString()
109
Conver Converts ts an XML object object into into a valid valid XML string string..
XMLDate.addDuration()
110
Returns Returns an XMLDate XMLDate object containing containing the new date/time date/time after adding adding the duration from the duration argument.
XMLDate.getDate()
110
Retur Returns ns a Java JavaScr Script ipt date/t date/time ime object object as a string string..
XMLDate.getDatum()
110
Returns Returns a Service Service Manager-for Manager-formatte matted d date/time date/time Datum object object in a string string
XMLDate.getGMTSCDateTim eString()
111
Returns Returns a Service Service Manager-for Manager-formatte matted d date/time date/time string string
XMLDate.getISODate()
111
Returns Returns a string string containing containing the date portion portion of a date/t date/time ime object object in ISO format
XMLDate.getISODateTimeStri ng()
111
Returns Returns a string string containing containing the date and time portion portion of date/time date/time object object in ISO format
XMLDate.getISODay()
112
Returns Returns a string string containing containing the day portion portion of date/t date/time ime object object in in ISO format format
XMLDate.getISOMonth()
112
Returns Returns a string string containing containing the month month portion portion of date/time date/time object object in ISO format
XMLDate.getISOTime()
112
Returns a string containing the time portion of date/time object in ISO format
XMLDate.getISOYear()
113
Returns a string containing the year portion of date/time object in ISO format
XMLDate.getSCDateTimeStrin g()
113
Returns Returns a Service Service Manager-for Manager-formatte matted d date/time date/time string string
XMLDate.JSDate()
113
Retur Returns ns a JavaScr JavaScript ipt date/t date/time ime object object
XMLDate.toSCDuration()
114
Returns a string containing the new Service Manager duration converted from an ISO 8601 duration
120
For more infor informatio mationn 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 softw software are support provides customer self-solve capabilities. It provides a fast and efficient way to access inte interactive ractive technical support tools needed to manage your business. As a valuable support customer, custom er, you can benefit by being able to:
Search for knowledge documents of interest Submit and track progre prog ress ss on support cases Submit enhancement requests online Download software patches Manage a support contr contract act Look up HP support cont co ntacts acts Review information abo about available services Enter discussions with other software customers Research and register for software training
support areas require that you register as an HP Passport user and sign in. Many Note: Most of the support also require an active support contract. To find more information about support access levels, go to the following URL: http://www.hp.com/manage http://www.hp.com/mana gementsoftware/access_level mentsoftware/access_level
To register for an HP Passp Passport ort ID, go to the following URL: http://www.managementsoft http://www.managements oftware.hp.com/passport-registration.html ware.hp.com/passport-registration.html