Jump to content
dynamitemedia

xmldom into array and then use outside function

Recommended Posts

dynamitemedia

i have the following snippet...   now its working but i have it inside a function and want to be able to use   $aThumb[$i]  outside the function in the rest of the script, i tried return and keep getting this error  "Invalid keyword at the start of this line.:"  

Global $iRows = UBound($a, $UBOUND_ROWS) 
    Global $iCols = UBound($a, $UBOUND_COLUMNS)

          $oID = $oID + 1
          $oURL = $oString.selectSingleNode("./url")
          $oName = $oString.selectSingleNode("./name")
          $oCategory = $oString.selectSingleNode("./category")
          $oThumb = $oString.selectSingleNode("./image")
          $oLanguage = $oString.selectSingleNode("./language")

         $aThumb = [$iRows]
         _ArrayAdd($aThumb, $oThumb.text)

         For $i = 1 To UBound($aThumb) - 1
             ConsoleWrite($oID & @TAB & $aThumb[$i] & @CRLF)
         Next
          
    Next
   ConsoleWrite( "rows: " & $iRows & @CRLF)

Thanks for your help

Share this post


Link to post
Share on other sites
AutoBert

Have you ever heard that functions can return a result? No, then smiley38.gif (Language Reference - User Functions)

Or show your (yet not) runable script, how you tried it.

Edited by AutoBert

Share this post


Link to post
Share on other sites
dynamitemedia

wow no need to be answer only to be rude...     thought was such a general question i had given enough info

Global Enum $iServerName, $iUBound

      Local $sText = ""
      For $i = 1 To Random(5, 20, 1)
         $sText &= Chr(Random(65, 122, 1))
      Next

       $link = "http://www.my site.to/api/live.xml?t=" & $sText   ; private api 
      ConsoleWrite($link  & @CRLF)

       Local $dBinary = InetRead($link)
       $sConverted = BinaryToString($dBinary)


       $strXMLStructure = "//channels/channel"
       $oXML = ObjCreate("Microsoft.XMLDOM")
       $oXML.loadXML($sConverted)

       $oStrings = $oXML.selectNodes($strXMLStructure)


       $oID = 0

Local $a
      For $oString In $oStrings

       If IsArray($a) Then
        ReDim $a[UBound($a)+1][$iUBound]
    Else
        Local $a[1][$iUBound]
    EndIf


    Global $iRows = UBound($a, $UBOUND_ROWS) ; Total number of rows. In this example it will be 10.
    Global $iCols = UBound($a, $UBOUND_COLUMNS) ; Total number of columns. In this example it will be 20.

          $oID = $oID + 1
          $oURL = $oString.selectSingleNode("./url")
          $oName = $oString.selectSingleNode("./name")
          $oCategory = $oString.selectSingleNode("./category")
          $oThumb = $oString.selectSingleNode("./image")
          $oLanguage = $oString.selectSingleNode("./language")

         Local $aThumb = [$iRows]
         _ArrayAdd($aThumb, $oThumb.text)

         For $i = 1 To UBound($aThumb) - 1
             ;ConsoleWrite($oID & @TAB & $aThumb[$i] & @CRLF)
            local $bThumb = 22
         Next
          ; ConsoleWrite($oID & @TAB & $oName.text & @TAB & $urlString & @TAB & $oThumb.text & @TAB & $oCategory.text & @TAB & $oLanguage.text & @CRLF )

            Return $bThumb

           Next

   ConsoleWrite( "rows: " & $iRows & @CRLF)

 

Share this post


Link to post
Share on other sites
kylomas

dymanitemedia,

"Return" is not allowed from GLOBAL scope, meaning that it is only used within a function, normally to return a value to the caller.

Your code is not runnable as several vars are undefined, perhaps some includes are missing?

kylomas

Also, I would make sure that $ostrings is an object and what are you trying to do with variable $a?

Edited by kylomas
additional info

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites
dynamitemedia

sorry the includes did get missed!  full code is here:
 

#include <ButtonConstants.au3>
#include <ComboConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <GUIListBox.au3>
#include <GuiListView.au3>
#include <GuiTab.au3>
#include <StaticConstants.au3>
#include <TabConstants.au3>
#include <WindowsConstants.au3>
#include <File.au3>
#include <Array.au3>
#include <Process.au3>
#include <Constants.au3>
#include <String.au3>
#include <Date.au3>

Global Enum $iServerName, $iUBound

      Local $sText = ""
      For $i = 1 To Random(5, 20, 1)
         $sText &= Chr(Random(65, 122, 1))
      Next

       $link = "http://my private api /api/live.xml?t=" & $sText
      ConsoleWrite($link  & @CRLF)

       Local $dBinary = InetRead($link)
       $sConverted = BinaryToString($dBinary)


       $strXMLStructure = "//channels/channel"
       $oXML = ObjCreate("Microsoft.XMLDOM")
       $oXML.loadXML($sConverted)

       $oStrings = $oXML.selectNodes($strXMLStructure)


       $oID = 0

Local $a
      For $oString In $oStrings

       If IsArray($a) Then
        ReDim $a[UBound($a)+1][$iUBound]
    Else
        Local $a[1][$iUBound]
    EndIf


    Global $iRows = UBound($a, $UBOUND_ROWS) ; Total number of rows. In this example it will be 10.
    Global $iCols = UBound($a, $UBOUND_COLUMNS) ; Total number of columns. In this example it will be 20.

          $oID = $oID + 1
          $oURL = $oString.selectSingleNode("./url")

          $oName = $oString.selectSingleNode("./name")
          $oCategory = $oString.selectSingleNode("./category")
          $oThumb = $oString.selectSingleNode("./image")
          $oLanguage = $oString.selectSingleNode("./language")

         Local $aThumb = [$iRows]
         _ArrayAdd($aThumb, $oThumb.text)

         For $i = 1 To UBound($aThumb) - 1
             ;ConsoleWrite($oID & @TAB & $aThumb[$i] & @CRLF)
            local $bThumb = 22
         Next
          ; ConsoleWrite($oID & @TAB & $oName.text & @TAB & $urlString & @TAB & $oThumb.text & @TAB & $oCategory.text & @TAB & $oLanguage.text & @CRLF )

            Return $bThumb

           Next

   ConsoleWrite( "rows: " & $iRows & @CRLF)

I need the thumbs , all of them in the gui...  the thing is i want to be able to grab more this just this xml, if it was meant to ONLY use one xml file i can hard code it work just fine...  but each api will have different xml structure and i need to code to work with each one
 

 

EDIT/ Additions

the $a is used to get the count of rows and columns

i use the rows to know how many buttons i will need to make

Edited by dynamitemedia
adding what $a is for

Share this post


Link to post
Share on other sites
dynamitemedia

so how can i use the info from this XML ? 

I want to use it to build the gui

Share this post


Link to post
Share on other sites
dynamitemedia

@jdelaney

Since you see, the expert at using the xml dom, any ideas how i can do this... I would really like to put this above in a function and still use each of the xml nodes if needed say i click on button 56  it would go to node 56 and get that info

Share this post


Link to post
Share on other sites
AutoBert

Seeing your script in #5 and checking:

>"C:\Program Files\AutoIt3\SciTE\AutoIt3Wrapper\AutoIt3Wrapper.exe" /prod /AU3Check /in "C:\Users\Bert\AutoIt3.My\Test\jhgfddfgh.au3"
+>12:43:50 Starting AutoIt3Wrapper v.14.801.2025.0 SciTE v.3.4.4.0   Keyboard:00000407  OS:WIN_81/  CPU:X64 OS:X64    Environment(Language:0407)
+>         SciTEDir => C:\Program Files\AutoIt3\SciTE   UserDir => C:\Users\Bert\AppData\Local\AutoIt v3\SciTE\AutoIt3Wrapper   SCITE_USERHOME => C:\Users\Bert\AppData\Local\AutoIt v3\SciTE 
>Running AU3Check (3.3.14.1)  from:C:\Program Files\AutoIt3  input:C:\Users\Bert\AutoIt3.My\Test\jhgfddfgh.au3
"C:\Users\Bert\AutoIt3.My\Test\jhgfddfgh.au3"(71,27) : error: 'Return' not allowed from global scope.
            Return $bThumb
~~~~~~~~~~~~~~~~~~~~~~~~~~^
C:\Users\Bert\AutoIt3.My\Test\jhgfddfgh.au3 - 1 error(s), 0 warning(s)
!>12:43:53 AU3Check ended. Press F4 to jump to next error.rc:2
+>12:43:53 AutoIt3Wrapper Finished.
>Exit code: 0    Time: 5.195

i am wondering about your ignorance.:

On ‎28‎.‎01‎.‎2016 at 10:31 PM, kylomas said:

"Return" is not allowed from GLOBAL scope, meaning that it is only used within a function, normally to return a value to the caller.

 This snippet:

Local $a
      For $oString In $oStrings

       If IsArray($a) Then
        ReDim $a[UBound($a)+1][$iUBound]
    Else
        Local $a[1][$iUBound]
    EndIf

show's me:

  • there you need the to learn the basic's. A variable $a just declared without any dimension testing against Array is nonsence. It couldn't be a array, nothing is happend.  So smiley38.gif work hard from the beginning to the end, including testing the examples of the needed functions.
  • or your script isn't complete, then post your complete script. 

Share this post


Link to post
Share on other sites
Melba23

AutoBert,

You have already been told once today about the manner in which you are replying - this is the second and final warning you get to change your ways. If your RTFM emoticon appears again - or if you express a similar unwelcoming attitude in future - your future in this community will be in serious jeopardy.

M23

  • Like 1

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites
dynamitemedia

these are help forums to ask for help..  why do you feel the need to insult and be rude to people asking for help?

that snippet that shows you   with your rant  was taken from here and it serves a purpose
https://www.autoitscript.com/forum/topic/179751-searching-fields-within-xml/?do=findComment&comment=1290314

I use it to get how many noded(rows) in the array

Global $iRows = UBound($a, $UBOUND_ROWS)

it works, is it right i am not 100% sure  but that works with giving me the right amount of nodes from the XML

as far as leaving the "Return" in there i  did uncomment it in my code.

and it is the whole code and works, when connected to the right  xml.   

I just want to make this a function  cause the images in the nodes will complete the gui.  

Instead of being rude maybe offering a alternate solution would be the way to go

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • AndreasNWWWWW
      By AndreasNWWWWW
      I got a question:  i am trying to run different functions based upon what i select in these radio buttons.(code below)
      it needs to check server 1. then run function 1 or function 2 after what i selected in the checkbox.
      once that function is done it moves to the next one, until it has been trough all 5 
       
      iv'e tried using while loops with different while $i equals to something but then i manualy need to go in and edit the script every time.
      #include <ButtonConstants.au3> #include <GUIConstantsEx.au3> #include <StaticConstants.au3> #include <WindowsConstants.au3> #Region ### START Koda GUI section ### Form= $Form1 = GUICreate("Form1", 615, 437, 192, 124) $Server2 = GUICtrlCreateLabel("Server2", 216, 95, 41, 17) $server1 = GUICtrlCreateLabel("Server1", 216, 72, 41, 17) $server4 = GUICtrlCreateLabel("Server4", 216, 144, 41, 17) $server3 = GUICtrlCreateLabel("Server3", 216, 119, 41, 17) $server5 = GUICtrlCreateLabel("Server5", 216, 170, 41, 17) $Start = GUICtrlCreateButton("Start", 240, 248, 147, 25) $Checkbox1 = GUICtrlCreateCheckbox("function1", 288, 72, 97, 17) $Checkbox2 = GUICtrlCreateCheckbox("function2", 392, 72, 97, 17) $Checkbox3 = GUICtrlCreateCheckbox("function1", 288, 96, 97, 17) $Checkbox4 = GUICtrlCreateCheckbox("function2", 392, 96, 97, 17) $Checkbox5 = GUICtrlCreateCheckbox("function1", 288, 120, 97, 17) $Checkbox6 = GUICtrlCreateCheckbox("function2", 392, 120, 97, 17) $Checkbox7 = GUICtrlCreateCheckbox("function1", 288, 144, 97, 17) $Checkbox8 = GUICtrlCreateCheckbox("function2", 392, 144, 97, 17) $Checkbox9 = GUICtrlCreateCheckbox("function1", 288, 170, 97, 17) $Checkbox10 = GUICtrlCreateCheckbox("function2", 392, 170, 97, 17) GUISetState(@SW_SHOW) #EndRegion ### END Koda GUI section ### While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit EndSwitch WEnd  
    • AnonymousX
      By AnonymousX
      Hello,
      So this may be more of a challenge of effective programming then specific to AutoIT but I want to solve this problem with AutoIT  so i'm putting it here. (If someone has a better language to solve with I'm all ears)
       
      So the task I'm trying to achieve is that I have multiple .CSV files that have: year, month, day, hour, value. I need to be able to sum up all the values that have the same date/time, then find which date and time has the maximum value.
       
      The problem is that each file may or may not have same amount of days/hours as the rest. So I need to devise a way to handle this. 
       
      Example:
      File A   File B   File C 2018 1 1  1:00 10   2018 1 1 2:00 10   2018 1 1  1:00 10 2018 1 1  2:00 12   2018 1 1 3:00 12   2018 1 2 1:00 12 2018 1 1  3:00 14   2018 1 1 4:00 14   2018 2 1  1:00 16 2018 2 1  1:00 16   2018 2 1  1:00 16              
       Answer I want to be spit out is Feb 1st 2018 at 2:00 with value of 48
       
      So far I've got code to store all .CSV files to an array, then a loop to go through each csv, but not sure how to effectively manipulate the data. Keep in mind each file has over 7000 time entry points.
       
      If anyone can solve this that would be pretty awesome! 
      #include <Array.au3> #include <File.au3> #include <MsgBoxConstants.au3> RefineData() Func RefineData() Local $i, $filenum, $file, $csvArray, $FilePath = @ScriptDir $fileList = _FileListToArrayRec($FilePath, "*.csv", 1) ;Create and array of all .csv files within folder Local $chkArray[UBound($fileList)][2] ;=====Loop through the .csv files within the folder====== For $filenum = 1 To UBound($fileList) - 1 Step 1 $file = $fileList[$filenum] $sFilePath = $FilePath & "\" & $file ;=====Create array based on csv file===== _FileReadToArray($sFilePath, $csvArray, $FRTA_NOCOUNT, ",") ;#### Operations here ###### next msgbox(0,"", "Date: " & $date_of_max & "Value: " & $maxVal );display solution endfunc  
    • corz
      By corz
      Associative Array Functions
      I've seen a couple of UDFs for this on the forum. One of them I quite like. But it's still nearly not as good as this method, IMHO.
      I don't recall if I discovered the "Scripting.Dictionary" COM object myself or if I got the original base code from somewhere online. I have recently searched the web (and here) hard for any AutoIt references to this, other than my own over the years I've been using this (in ffe, etc..), and I can find nothing, so I dunno. If anyone does, I'd love to give credit where it's due; this is some cute stuff! It could actually be all my own work! lol
      At any rate, it's too useful to not have posted somewhere at autoitscript.com, so I've put together a wee demo.
      For those who haven't heard of the COM "Scripting.Dictionary".. 
      If you've ever coded in Perl or PHP (and many other languages), you know how useful associative arrays are. Basically, rather than having to iterate through an array to discover it's values, with an associative array you simply pluck values out by their key "names".
      I've added a few functions over the years, tweaked and tuned, and this now represent pretty much everything you need to easily work with associative arrays in AutoIt. En-joy!
      The main selling point of this approach is its simplicity and weight. I mean, look at how much code it takes to work with associative arrays! The demo is bigger than all the functions put together! The other selling point is that we are using Windows' built-in COM object functions which are at least theoretically, fast and robust.
      I've used it many times without issues, anyhow, here goes..
      ; Associative arrays in AutoIt? Hells yeah! ; Initialize your array ... global $oMyError = ObjEvent("AutoIt.Error", "AAError") ; Initialize a COM error handler ; first example, simple. global $simple AAInit($simple) AAAdd($simple, "John", "Baptist") AAAdd($simple, "Mary", "Lady Of The Night") AAAdd($simple, "Trump", "Silly Man-Child") AAList($simple) debug("It is said that Trump is a " & AAGetItem($simple, "Trump") & ".", @ScriptLineNumber);debug debug("") ; slightly more interesting.. $ini_path = "AA_Test.ini" ; Put this prefs section in your ini file.. ; [test] ; foo=foo value ; foo2=foo2 value ; bar=bar value ; bar2=bar2 value global $associative_array AAInit($associative_array) ; We are going to convert this 2D array into a cute associative array where we ; can access the values by simply using their respective key names.. $test_array = IniReadSection($ini_path, "test") for $z = 1 to 2 ; do it twice, to show that the items are *really* there! for $i = 1 to $test_array[0][0] $key_name = $test_array[$i][0] debug("Adding '" & $key_name & "'..");debug ; key already exists in "$associative_array", use the pre-determined value.. if AAExists($associative_array, $key_name) then $this_value = AAGetItem($associative_array, $key_name) debug("key_name ALREADY EXISTS! : =>" & $key_name & "<=" , @ScriptLineNumber);debug else $this_value = $test_array[$i][1] ; store left=right value pair in AA if $this_value then AAAdd($associative_array, $key_name, $this_value) endif endif next next debug(@CRLF & "Array Count: =>" & AACount($associative_array) & "<=" , @ScriptLineNumber);debug AAList($associative_array) debug(@CRLF & "Removing 'foo'..");debug AARemove($associative_array, "foo") debug(@CRLF & "Array Count: =>" & AACount($associative_array) & "<=" , @ScriptLineNumber);debug AAList($associative_array) debug(@CRLF & "Removing 'bar'..");debug AARemove($associative_array, "bar") debug(@CRLF & "Array Count: =>" & AACount($associative_array) & "<=" , @ScriptLineNumber);debug AAList($associative_array) quit() func quit() AAWipe($associative_array) AAWipe($simple) endfunc ;; Begin AA Functions func AAInit(ByRef $dict_obj) $dict_obj = ObjCreate("Scripting.Dictionary") endfunc ; Adds a key and item pair to a Dictionary object.. func AAAdd(ByRef $dict_obj, $key, $val) $dict_obj.Add($key, $val) If @error Then return SetError(1, 1, -1) endfunc ; Removes a key and item pair from a Dictionary object.. func AARemove(ByRef $dict_obj, $key) $dict_obj.Remove($key) If @error Then return SetError(1, 1, -1) endfunc ; Returns true if a specified key exists in the associative array, false if not.. func AAExists(ByRef $dict_obj, $key) return $dict_obj.Exists($key) endfunc ; Returns a value for a specified key name in the associative array.. func AAGetItem(ByRef $dict_obj, $key) return $dict_obj.Item($key) endfunc ; Returns the total number of keys in the array.. func AACount(ByRef $dict_obj) return $dict_obj.Count endfunc ; List all the "Key" > "Item" pairs in the array.. func AAList(ByRef $dict_obj) debug("AAList: =>", @ScriptLineNumber);debug local $k = $dict_obj.Keys ; Get the keys ; local $a = $dict_obj.Items ; Get the items for $i = 0 to AACount($dict_obj) -1 ; Iterate the array debug($k[$i] & " ==> " & AAGetItem($dict_obj, $k[$i])) next endfunc ; Wipe the array, obviously. func AAWipe(ByRef $dict_obj) $dict_obj.RemoveAll() endfunc ; Oh oh! func AAError() Local $err = $oMyError.number If $err = 0 Then $err = -1 SetError($err) ; to check for after this function returns endfunc ;; End AA Functions. ; debug() (trimmed-down version) ; ; provides quick debug report in your console.. func debug($d_string, $ln=false) local $pre ; For Jump-to-Line in Notepad++ if $ln then $pre = "(" & $ln & ") " & @Tab ConsoleWrite($pre & $d_string & @CRLF) endfunc  
      ;o) Cor
    • wsc77320
      By wsc77320
      Maybe I am trying this all wrong, but hope someone can help. I have a GUI and want to click a button which will start a function to get a folder location. Then I need to pass that location to a variable to use outside the function. Here is a sample of the code;It prompts to choose a file location and the message box displays the choice but that is all inside the function. I need to pass the path selected outside the function. OR need a different way of doing this, maybe my approach is wrong.
      $Label_Drive=GUICtrlCreateLabel("Use the select button and choose where profiles will be stored.", 15, 120, 240, 25)
      $BTN_Set_BKP_Path = GUICtrlCreateButton("Select Location", 250, 120, 90, 30) ;left,top,width,heigth
      GUICtrlSetOnEvent($BTN_Set_BKP_Path, "Location")
       
      Func Location()
      $BKP_Path = FileSelectFolder("Select a folder where profiles will be stored.", "c:\")
      MsgBox(0,"Select Path", "You set the path as " & $BKP_Path)
      EndFunc
       
      $Label_BKP_Path=GUICtrlCreateLabel("Current path is " & $BKP_Path & ".", 15, 150, 300, 25)
       
       
    • Ascer
      By Ascer
      Hello.
      A couple week ago i've started learning API Interface for different websites. In this fact sometimes you have to encode your "photo" or "document.body" to send request.
      Functions to encode and decode Base64 was already created by others. Unfortunately i have troubles with running it on Windows R 2008, also speed was terrible.
      I try to find alternative way to code data. 
      I've read about Microsoft "XMLDOM" and created a one simple function to Encode / Decode data to base64binary, base64url
      Thanks for Ghads on Wordpress i coverted a part of his lines from VBscript to AutoIT
      ;============================================================================================================================== ; Function: base64($vCode [, $bEncode = True [, $bUrl = False]]) ; ; Description: Decode or Encode $vData using Microsoft.XMLDOM to Base64Binary or Base64Url. ; IMPORTANT! Encoded base64url is without @LF after 72 lines. Some websites may require this. ; ; Parameter(s): $vData - string or integer | Data to encode or decode. ; $bEncode - boolean | True - encode, False - decode. ; $bUrl - boolean | True - output is will decoded or encoded using base64url shema. ; ; Return Value(s): On Success - Returns output data ; On Failure - Returns 1 - Failed to create object. ; ; Author (s): (Ghads on Wordpress.com), Ascer ;=============================================================================================================================== Func base64($vCode, $bEncode = True, $bUrl = False) Local $oDM = ObjCreate("Microsoft.XMLDOM") If Not IsObj($oDM) Then Return SetError(1, 0, 1) Local $oEL = $oDM.createElement("Tmp") $oEL.DataType = "bin.base64" If $bEncode then $oEL.NodeTypedValue = Binary($vCode) If Not $bUrl Then Return $oEL.Text Return StringReplace(StringReplace(StringReplace($oEL.Text, "+", "-"),"/", "_"), @LF, "") Else If $bUrl Then $vCode = StringReplace(StringReplace($vCode, "-", "+"), "_", "/") $oEL.Text = $vCode Return $oEL.NodeTypedValue EndIf EndFunc ;==>base64  
       
×