Jump to content

xml.udf -- failing to get how to use it


Recommended Posts

Hello,

once more I have to see, that my knowledge about XML is too poor, even to use this existing XML UDF

If it should be a better approach to make use of StringRegEx, or maybe a totally different approach, any suggestions will be mostly appreciated.

 

I downloaded the ZIP XML_1.1.1.13 and tried to get how to use it from the sample AU3 files included in that ZIP file, well, I don't really get it😵

 

 

What I want to do:

My mobile phone's backup contain all the contacts in an XML file. This is an example of such a file, backupinfo.xml, shortened to show just one fictive entry:

 

<?xml version="1.0" encoding="utf-8" ?>
<ContactRecords>
    <contact>
        <structuredName>
            <displayName>Max Mustermann</displayName>
            <givenName>Max</givenName>
            <familyName>Mustermann</familyName>
            <prefixName />
            <middleName />
            <suffixName />
            <phoneticGivenName />
            <phoneticMiddleName />
            <phoneticFamily />
        </structuredName>
        <organization>
            <company>Schlosserei Mustermann GmbH</company>
            <department />
            <title />
        </organization>
        <phones>
            <phone>
                <number>07652 881 8181</number>
                <type>home</type>
                <customLabel />
            </phone>
            <phone>
                <number>0 800 435 2758</number>
                <type>work</type>
                <customLabel />
            </phone>
            <phone>
                <number>+49 160 4321 222</number>
                <type>mobile</type>
                <customLabel />
            </phone>
        </phones>
        <emails />
        <addresses />
        <ims />
        <WebSites />
        <Events />
        <note />
        <nickName />
        <photo />
        <netPhone />
        <groups>
            <group>
                <groupName>Ungrouped</groupName>
            </group>
        </groups>
    </contact>
</ContactRecords>

 

Basically I want to search my mobile's contacts for phone numbers to, to see, what contact they belong to. Propably it will make the task much more easy, when standardizing the mobile's contact XML to hold all numbers in "international-notation-without-any-whitespaces" (thats no problem):

 

<?xml version="1.0" encoding="utf-8" ?>
<ContactRecords>
    <contact>
        <structuredName>
            <displayName>Max Mustermann</displayName>
            <givenName>Max</givenName>
            <familyName>Mustermann</familyName>
            <prefixName />
            <middleName />
            <suffixName />
            <phoneticGivenName />
            <phoneticMiddleName />
            <phoneticFamily />
        </structuredName>
        <organization>
            <company>Schlosserei Mustermann GmbH</company>
            <department />
            <title />
        </organization>
        <phones>
            <phone>
                <number>+4976528818181</number>
                <type>home</type>
                <customLabel />
            </phone>
            <phone>
                <number>+498004352758</number>
                <type>work</type>
                <customLabel />
            </phone>
            <phone>
                <number>+491604321222</number>
                <type>mobile</type>
                <customLabel />
            </phone>
        </phones>
        <emails />
        <addresses />
        <ims />
        <WebSites />
        <Events />
        <note />
        <nickName />
        <photo />
        <netPhone />
        <groups>
            <group>
                <groupName>Ungrouped</groupName>
            </group>
        </groups>
    </contact>
</ContactRecords>

 

What I would like to get from the XML file as a result, e.g. searching the phone number "+491604321222"

  1. Present in XML  or not (true)
  2. if present then return the values for...
  3. type (mobile)
  4. givenname (Max)
  5. familyname (Mustermann)
  6. company (Schlosserei Mustermann GmbH)
  7. optional: Other node names and their values within that contact, when not "empty" (like in this examle <emails /> or <middlename />)

 

The values from #2 - #6 would be perfect when returned in a 2D Array, Col0 = name, Col1 = value.

Regards, Rudi.

 

Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Link to post
Share on other sites

Well structured data makes me most often use StringRegExp:

 

$aArray = StringRegExp($sFileRead, '(?i)(?s)<ContactRecords>.*?<displayName>(.*?)</displayName>.*?<company>(.*?)</company>.*?<number>(.*?)</number>(?-s)\r?\n\s*<type>(.*?)</type>(?s).*?<number>(.*?)</number>(?-s)\r?\n\s*<type>(\w+)</type>(?s).*?<number>(.*?)</number>(?-s)\r?\n\s*<type>(\w+)</type>(?s).*?(?=</ContactRecords>)', 4)

Local $aMatch = 0
For $i = 0 To UBound($aArray) - 1
    $aMatch = $aArray[$i]
    For $j = 1 To UBound($aMatch) - 1
        ConsoleWrite($aMatch[$j] & @CRLF)
    Next
    ConsoleWrite(@CRLF)
Next

but, of course, others will differ.

Link to post
Share on other sites

I'm on my vacation/holidays 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * for other useful stuff click the following button:

Spoiler

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

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE *

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2021-10-18

Link to post
Share on other sites

 

On 8/20/2020 at 4:54 PM, rudi said:

once more I have to see, that my knowledge about XML is too poor, even to use this existing XML UDF

... any suggestions will be mostly appreciated.


Since you are having such a hard time, here's an example, using the xml udf, that may help get you started.  ;)  It is based on the xml structure that you provided above.  It loads contact information, for each contact, into a 2D array that can be searched however you choose.
 

#AutoIt3Wrapper_AU3Check_Parameters=-w 3 -w 4 -w 5 -w 6 -d

#include <Constants.au3>
#include <Array.au3>
#include <MyIncludes\XML\xml.au3>  ;<== Modify as needed

xml_example()

Func xml_example()
    Const $XML_FILE = @ScriptDir & "\test.xml" ;<== Modify as needed

    Local $oXML, $oContacts
    Local $aContacts[0][7]
    Local $sDisplayName, $sFirstName, $sLastName, $sCompany, $sHomePhone, $sWorkPhone, $sMobilePhone

    ;Create XML object
    $oXML = _XML_CreateDOMDocument()
    If @error Then Exit MsgBox($MB_ICONERROR, "ERROR", "XML object creation failed - @error = " & @error)

    ;Load xml file
    _XML_Load($oXML, $XML_FILE)
    If @error Then Exit MsgBox($MB_ICONERROR, "ERROR", "Loading of XML failed - @error = " & @error)

    ;Get collection of contact nodes
    $oContacts = _XML_SelectNodes($oXML, "/ContactRecords/contact")
    If @error Then Exit MsgBox($MB_ICONERROR, "ERROR", "Error getting contact nodes - @error = " & @error)

    ;Load contact information into the array
    For $oContact in $oContacts
        ;Populate the fields
        $sDisplayName = _XML_GetValue($oContact, "structuredName/displayName")[1]
        $sFirstName   = _XML_GetValue($oContact, "structuredName/givenName")[1]
        $sLastName    = _XML_GetValue($oContact, "structuredName/familyName")[1]
        $sCompany     = _XML_GetValue($oContact, "organization/company")[1]

        $sHomePhone = ""
        If _XML_NodeExists($oContact, "phones/phone[type='home']/number") Then _
            $sHomePhone = _XML_GetValue($oContact, "phones/phone[type='home']/number")[1]

        $sWorkPhone = ""
        If _XML_NodeExists($oContact, "phones/phone[type='work']/number") Then _
            $sWorkPhone = _XML_GetValue($oContact, "phones/phone[type='work']/number")[1]

        $sMobilePhone = ""
        If _XML_NodeExists($oContact, "phones/phone[type='mobile']/number") Then _
            $sMobilePhone = _XML_GetValue($oContact, "phones/phone[type='mobile']/number")[1]

        ;Add row to the array
        _ArrayAdd($aContacts, _
            $sDisplayName & "|" & _
            $sFirstName   & "|" & _
            $sLastName    & "|" & _
            $sCompany     & "|" & _
            $sHomePhone   & "|" & _
            $sWorkPhone   & "|" & _
            $sMobilePhone)
    Next

    _ArrayDisplay($aContacts, "Contacts", "", 0, Default, _
                  "Display Name|First Name|Last Name|Company|Home Phone|Work Phone|Mobile Phone")

EndFunc

image.png.d54eae949159726ce66c512d08795d33.png

test.xml

Edited by TheXman
Tidy up the script / Added test.xml file
Link to post
Share on other sites
On 8/22/2020 at 10:27 AM, Jos said:

The shown information is not real I hope? :) 

Jos

<cite>

... . This is an example of such a file, backupinfo.xml, shortened to show just one fictive entry:

</cite>

 

Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Link to post
Share on other sites
  • 4 months later...

@TheXman

thanks a lot for your great example script.

I recognized, that the XML structure for the part of the phone numbers is giving me some additional constraints:

  1. phone number types might show up more than once, e.g. if someone has two private or to work mobile phones.
  2. phone numbers can have custom lables.

So I'd like to ask, how to catch all the numbers and their "custom lable name(s)", in case that node is populated. (Your example result array is super nice, but it's not required to have fixed collumns, it's sufficent to me when I just can catch all the phone numbers and their custom or standard "label names")

 

        <phones>
            <phone>
                <number>+49 163 1234567</number>
                <type>mobile</type>
                <customLabel />
            </phone>
            <phone>
                <number>+49 163 9759759</number>
                <type>mobile</type>
                <customLabel />
            </phone>
            <phone>
                <number>+49 9335 1111111</number>
                <type>home</type>
                <customLabel />
            </phone>
            <phone>
                <number>+4993211234567</number>
                <type>custom</type>
                <customLabel>Küche</customLabel>
            </phone>
        </phones>

of course these all are fictive numbers 😉

 

the result pairs that would help me, order doesn't matter, would be:

mobile|+49 163 1234567
mobile|+49 163 9759759
home|+49 9335 1111111
Küche|+4993211234567

I didn't solve to get in the first step a list of the four nodes <phone></phone>

and in a second step the list of the sub-nodes <number></number>, <type></type> and <customlabel>value</customlabel> or <customlabel />

 

I guess, that  "<customlabel />" is an existing, but "empty" node?? for the function _XML_NodeExists() ? (the function will not return FALSE?)

Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Link to post
Share on other sites
8 minutes ago, rudi said:

@TheXman

thanks a lot for your great example script.

I guess a belated, 5 months late, thanks is better than no thanks at all.  ;)  But it seems that the only reason you are @tagging and thanking me is because you would like my help again.  :huh2:    I usually don't help people that don't appreciate it.  Maybe my example in the post below may help you.  Good luck.  :bye:

 

Link to post
Share on other sites

Hello @TheXman
please accept my apologies to have missed to drop a immediate thank you. 😞

 

I've lost touch with this task -- basically I wanted to dig in immediately  -- and of course to thank you, expecting that I will run in some constraints I don't have the XML knowledge to get it solved on my own...

CU, Rudi.

Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Link to post
Share on other sites

Thanks for your example,

still not getting to my propably really simple goal, to see a list of "child nodes" -- :mad2:

#include <Debug.au3>
#include <Constants.au3>
#include <Array.au3>
#include "C:\temp\XML_1.1.1.13\XML.au3"  ;<== Modify as needed


$PhoneBookXML=@scriptdir & "\SamplePhoneBook-2.xml"

; ShellExecute($PhoneBookXML)


xml_example()

Func xml_example()
    Const $XML_FILE = $PhoneBookXML ;<== Modify as needed

    Local $oXML, $oContacts

    ;Create XML object
    $oXML = _XML_CreateDOMDocument()
    If @error Then
        Exit MsgBox($MB_ICONERROR, "ERROR", "XML object creation failed - @error = " & @error)
    Else
        ConsoleWrite("Done: $oXML = _XML_CreateDOMDocument()" & @CRLF)
    EndIf


    ;Load xml file
    _XML_Load($oXML, $XML_FILE)
    If @error Then
        Exit MsgBox($MB_ICONERROR, "ERROR", "Loading of XML failed - @error = " & @error)
    Else
        ConsoleWrite("Done: _XML_Load($oXML, $XML_FILE)" & @CRLF)
    EndIf

    ;Get collection of contact nodes
    $oContacts = _XML_SelectNodes($oXML, "/ContactRecords/contact")
    If @error Then Exit MsgBox($MB_ICONERROR, "ERROR", "Error getting contact nodes - @error = " & @error)

    For $oContact in $oContacts
        ;Populate the fields

        if _XML_NodeExists($oContact,"phones") Then _
            ConsoleWrite('True: _XML_NodeExists($oContact,"phones")' & @CRLF)

        if _XML_NodeExists($oContact,"phones/phone") Then _
            ConsoleWrite('True: _XML_NodeExists($oContact,"phones/phone")' & @CRLF)

        if _XML_NodeExists($oContact,"phones/phone/notpresent") Then
            ConsoleWrite('True: _XML_NodeExists($oContact,"phones/phone/notpresent")' & @CRLF)
        Else
            ConsoleWrite('False: _XML_NodeExists($oContact,"phones/phone/notpresent")' & @CRLF)
        EndIf


        ; trying to get a list  of next XML LEVEL elements -- howto use the results?
        $aStructuredName=_XML_GetChildren($oXML, "ContactRecords/contact")
        $Err=@error
        if IsArray($aStructuredName) Then
            _DebugArrayDisplay($aStructuredName) ; see screenshot below
        Else
            MsgBox(262144, VarGetType($aStructuredName) , "No array was returned" & @CRLF & "$aStructuredName = " & $aStructuredName & @CRLF & "@Error = " & $Err,3)
        EndIf
        $sHomePhone = ""
        If _XML_NodeExists($oContact, "phones/phone[type='home']/number") Then _
            $sHomePhone = _XML_GetValue($oContact, "phones/phone[type='home']/number")[1]

        $sWorkPhone = ""
        If _XML_NodeExists($oContact, "phones/phone[type='work']/number") Then _
            $sWorkPhone = _XML_GetValue($oContact, "phones/phone[type='work']/number")[1]

        $sMobilePhone = ""
        If _XML_NodeExists($oContact, "phones/phone[type='mobile']/number") Then _
            $sMobilePhone = _XML_GetValue($oContact, "phones/phone[type='mobile']/number")[1]
        ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $sHomePhone = ' & $sHomePhone & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
        ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $sWorkPhone = ' & $sWorkPhone & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
        ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $sMobilePhone = ' & $sMobilePhone & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console
    Next
EndFunc

function definition header:

; Return values .: On Success    - Returns an array where:
;                  |$array[0][0] = Size of array
;                  |$array[1][0] = Name
;                  |$array[1][1] = Text
;                  |$array[1][2] = NameSpaceURI
;                  |...

image.png.ee774f0e9a4c9ffb1007928f4b78f324.png

I absolutely miss the meaning of this result array:

  • just one node structuredName, showing up 10 times
  • also just one node company, showing up 4 times
  • phones showing up 5 times I guess reflects one node "phones", plus 4 sub-nodes "phone" ?
  • And just column[0] = name's values are populated. Column[1]=Text and column[2]=NameSpaceURI remain empty for all rows?

That's all exciting and frustrating at the same time.

XML file:

<?xml version="1.0" encoding="utf-8" ?>
<ContactRecords>
    <contact>
		<structuredName>
			<displayName>Peter </displayName>
			<givenName>Peter</givenName>
			<familyName>Miller</familyName>
			<prefixName />
			<middleName />
			<suffixName />
			<phoneticGivenName />
			<phoneticMiddleName />
			<phoneticFamily />
		</structuredName>
		<organization>
			<company>CorpName</company>
			<department />
			<title />
		</organization>
        <phones>
            <phone>
                <number>+49 163 1234567</number>
                <type>mobile</type>
                <customLabel />
            </phone>
            <phone>
                <number>+49 163 9759759</number>
                <type>mobile</type>
                <customLabel />
            </phone>
            <phone>
                <number>+49 9335 1111111</number>
                <type>home</type>
                <customLabel />
            </phone>
            <phone>
                <number>+4993211234567</number>
                <type>custom</type>
                <customLabel>Kitchen</customLabel>
            </phone>
        </phones>
    </contact>
</ContactRecords>

 

Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Link to post
Share on other sites

Hello @TheXman

could you pls point me the right direction to investigate the internal node structure of an XML document, and to investigate the values of these nodes, for XML documents, that have a *VARIABLE* structure below the top level nodes?

I've tried various ways to grab this information, but I have to admit that my XML knowlege is definitely too poor for even this propably simple task. (also tried PowerShell, just trying to get that info...)

TIA, Rudi.

semper volens accipere auxilium 

 

Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Link to post
Share on other sites
12 hours ago, rudi said:

could you pls point me the right direction to investigate the internal node structure of an XML document, and to investigate the values of these nodes, for XML documents, that have a *VARIABLE* structure below the top level nodes?

I've given you 2 very good examples already.  The first example was the original one in this post.  The "contact" element has an unknown number of instances.  You could process your "phone" elements the same way (select the collection of phone nodes -- for a given contact node -- and then process that collection).  The second example is in the link that I provided.  It uses a different way of accessing a node that has a "variable" number of instances.  Basically. it gets a count of the number of nodes first and then processes them as indexed items.  So I don't know how much more "pointing" you in the right direction I can do because you don't seem to be absorbing the information that I've provided. 

You seemed to be more interested in getting a solution to your problem than learning how to solve it.  If that's true and you've read my About Me, then you should know that I'm the wrong person to ask.  If you want my help, then you need to show that you are trying to learn and have hit an obstacle that you need help understanding why you hit it and what you can do to get around it.  You can do that by showing your script attempt (or a running example), point out where you think you are having an issue, and ask specific/detailed questions.  Your previous attempt uses _XML_GetChildren(), which is not used in either of my examples.  Obviously, given the array that is returned, it is being use incorrectly and is not what I would use to gather the "phone" information (at least not in the way that you tried to implement it).

Here's a hint on selecting the "phone" nodes:

  • XPath from the root:  "/ContactRecords/contact/phones/phone"
  • XPath relative to "contact":  "phones/phone"
Edited by TheXman
Link to post
Share on other sites

No error handling...but simple example.  Add the data to an array, or do what you will with it

 

Local $oXML = ObjCreate("Microsoft.XMLDOM")
$oXML.Load(@DesktopDir & "/test.xml")
$oContacts = $oXML.selectNodes("//contact")
For $oContact In $oContacts
    $oPhones = $oContact.selectNodes("./phones/phone")
    For $oPhone In $oPhones
        $oNumber = $oPhone.selectSingleNode("./number")
        $oType   = $oPhone.selectSingleNode("./type")
        $oCustom = $oPhone.selectSingleNode("./customLabel")
        ConsoleWrite("$oNumber=[" & $oNumber.text & "], $oType=[" & $oType.text & "], $oCustom=[" & $oCustom.text & "]" & @CRLF)
    Next
Next

output:

$oNumber=[+49 163 1234567], $oType=[mobile], $oCustom=[]
$oNumber=[+49 163 9759759], $oType=[mobile], $oCustom=[]
$oNumber=[+49 9335 1111111], $oType=[home], $oCustom=[]
$oNumber=[+4993211234567], $oType=[custom], $oCustom=[Kitchen]

Edited by jdelaney
IEbyXPATH-Grab IE DOM objects by XPATH IEscriptRecord-Makings of an IE script recorder ExcelFromXML-Create Excel docs without excel installed GetAllWindowControls-Output all control data on a given window.
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
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By mLipok
      I was asking @eltorro serveral times for any support  for XML DOM wrapper (COM) - with no success  
          So I took matters into my hands ..... I want to present XMLWrapperEx.au3 - BETA Version
      Want to join to the project ?
       
      Here is some description:
      ; #INDEX# ======================================================================================================================= ; Title .........: XMLWrapperEx.au3 ; AutoIt Version : 3.3.10.2++ ; Language ......: English ; Description ...: Functions to use for reading and writing XML using msxml. ; Remarks .......: BETA Version ; Author ........: mLipok ; Version .......: "1.1.1.01" ; _XML_MiscProperty_UDFVersion() #CS This UDF is created on the basis of: https://www.autoitscript.com/forum/topic/19848-xml-dom-wrapper-com/ For this reason, I attach also the last known (to me) previous version ($_XMLUDFVER = "1.0.3.98" _XMLDomWrapper_1.0.3.98_CN.au3 ) For the same reason I continue to recognize the achievements of the work of my predecessors (they are still noted in each Function header). . . . . !!!!!!!!! This is BETA VERSION (all could be changed) !!!!!!!!! . . . WORK IN PROGRES INFORMATION: For now 2015-09-01 the descripion (Function Header) can not entirely correctly describe the function. TODO: in many places I used "TODO" as a keyword to find what should be done in future . I want to: PREVENT THIS: The unfortunate nature of both the scripts is that the func return results are strings or arrays instead of objects. .     I want to: USE THIS CONCEPT:     .   All function should use Refernce to the object as first Function parameter     .   All function should return in most cases objects. There should be separate functions to Change Object collection to array     .   All function should use COM Error Handler in local scope.     .   All function should return @error which are defined in #Region XMLWrapperEx.au3 - @ERROR Enums     .    All function should have the same naming convention     .    All variables should have the same naming convention     .    There should not to be any Global Variable - exception is $g__oXMLDOM_Events     .   It should be possible easy to use XML DOM Events     .        https://msdn.microsoft.com/en-us/library/ms764697(v=vs.85).aspx     .   It should be possible easy to Debug     .    Ultimately, you should be able to do anything with your XML without having to use your own Error Handler. #CE  
      More info inside zip archive.
      This UDF can be downloaded from here:
      REMARK:
      This UDF was formerly named:   XMLWrapperEx.au3 
       
    • By Luigi
      Greetings,
       
      Someone can help-me to translate this Python's code to AutoIt?
       
      Python (source: https://repl.it/repls/InstructiveDarkslategreyJackrabbit)
      str = 'age=12,name=bob,hobbies="games,reading",phrase="I\'m cool!"' key = "" val = "" dict = {} parse_string = False parse_key = True # parse_val = False for c in str: print(c) if c == '"' and not parse_string: parse_string = True continue elif c == '"' and parse_string: parse_string = False continue if parse_string: val += c continue if c == ',': # terminate entry dict[key] = val #add to dict key = "" val = "" parse_key = True continue elif c == '=' and parse_key: parse_key = False elif parse_key: key += c else: val+=c dict[key] = val print(dict.items()) Python's output:
      [('phrase', "I'm cool!"), ('age', '12'), ('name', 'bob'), ('hobbies', 'games,reading')] AutoIt
      #include-once #include <Array.au3> #include <StringConstants.au3> Global $opt $opt = "estado = """" , cep = """", idade=32, nome = ""Luismar"", campo=""campo = campo""" $opt = "age=12,name=bob,hobbies=""games,reading"",phrase=""I\'m cool!""" ConsoleWrite($opt & @LF) Local $arr = StringSplit($opt, "", $STR_CHRSPLIT) Local $key = "" Local $val = "" Local $dict = ObjCreate("Scripting.Dictionary") Local $parse_string = False Local $parse_key = True Local $c For $ii = 1 To $arr[0] $c = $arr[$ii] If $c == '"' And Not $parse_string Then $parse_string = True ContinueLoop ElseIf $c == """" And $parse_string Then $parse_string = False ContinueLoop EndIf If $parse_string Then $val &= $c ContinueLoop EndIf If $c = "," Then $dict.Add($key, $val) $key = "" $val = "" $parse_key = True ContinueLoop ElseIf $c == "=" And $parse_key Then $parse_key = False ElseIf $parse_key Then $key &= $c Else $val &= $c EndIf Next $dict.Add($key, $val) ; missing this line... For $each In $dict ConsoleWrite($each & " = " & $dict.Item($each) & @LF) Next AutoIt's output
      age=12,name=bob,hobbies="games,reading",phrase="I\'m cool!" age = 12 name = bob hobbies = games,reading  
      Best regards.
       
    • By VinMe
      Dear all, i am unable to open a xml file to excel in the "xml table format" Please help me out in where i am missing
      Local $strFileToOpen = _WinAPI_OpenFileDlg('Select xml file', @WorkingDir, 'All Files(*.*)', 1, '', '', BitOR($OFN_PATHMUSTEXIST, $OFN_FILEMUSTEXIST, $OFN_HIDEREADONLY)) Global $xlXmlLoadImportToList = 2 ; Places the contents of the XML data file in an XML table $oExcel = _Excel_Open() $oWorkbook1=$oExcel.Workbooks.OpenXML($strFileToOpen, "", $xlXmlLoadImportToList) If $strFileToOpen <> False Then     Local $oWorkbook1 = _Excel_BookOpen($oExcel, $strFileToOpen) EndIf Error i am getting is:
      ......\81e_Compare_v1.au3" (46) : ==> The requested action with this object has failed.:
      $oWorkbook1=$oExcel.Workbooks.OpenXML($strFileToOpen, "", $xlXmlLoadImportToList)
      $oWorkbook1=$oExcel.Workbooks^ ERROR
      >Exit code: 1    Time: 7.338
    • By ijourneaux
      I have been using the XML UDF successfully for sometime. I am now tring to add in error handling for some bad XML files I run into.
      $oXmlDoc = _XML_CreateDOMDocument(Default) _XML_Load($oXmlDoc,$sFileXML) ;<== ENTER XML FILE PATH HERE If @error Then ; ConsoleWrite(StringFormat("_XML_load error - @error = %s", @error) & @CRLF) ; ConsoleWrite("-" & $sFileXML & @CRLF) Exit -1 EndIf ConsoleWrite("-" & $sFileXML & @CRLF) ;If no specified nodes exist, log error and exit If Not _XML_NodeExists($oXmlDoc, "//Property") Then ; ConsoleWrite("No specified nodes exist" & @CRLF) Exit -1 EndIf ;Get number of Property nodes $oProperties = _XML_SelectNodes($oXmlDoc,"//Property/Data") $iNodeCount = @extended $oParents = $oXmlDoc.SelectSingleNode("//Property[@Name='Parents']/Data") There are no error upto this point. The XML file I am trying to handle has a Data node but when I try to
      $sParam = StringSplit($oParents.text, ";") I get a fatal error (requested action on object failed). How can I test for the problem before I try to do the string split? I tried using @error, and testing $oParents but no luck.
      Appreciate any tips.
    • By ijourneaux
      I am trying to read an XML file that looks like the following. I am particularly interested in the ParameterNames and ParameterValues
       
      I was able to read a simplier XML file using
      $oXML.load("DataForwardSettings.xml") Local $oInfos = $oXML.selectnodes("//Database") ; or //Info or //Data//Info or //Values/Info  but have not been able to read
      <?xml version="1.0"?> <Entities> <Entity RecordType="TrendData"> <Property Name="AlarmLimitsSetNumber" IsReadOnly="False" ValueType="System.Int32">8</Property> <Property Name="AnalysisParamaterSetNumber" IsReadOnly="False" ValueType="System.Int32">8</Property> <Property Name="ParameterNames" IsReadOnly="True" IsList="True" ListType="List<string>" ValueType="Array" ArrayType="System.String" Count="12">System.Collections.Generic.List`1[System.String]<Data>OVERALL|PK-PK WAVEFORM|HFD|CREST FACTOR|SYNC 1-6|1X|2X|3X-4X|FTF|BSF|BPFO|BPFI</Data></Property> <Property Name="ParameterValues" IsReadOnly="True" IsList="True" ListType="List<float>" ValueType="Array" ArrayType="System.Single" Count="12">System.Collections.Generic.List`1[System.Single]<Data>0.04706,0.27951,0.02640,4.85608,0.03494,0.01727,0.02256,0.01993,0.00207,0.00060,0.00178,0.00221</Data></Property> <Property Name="NumberOfParameters" IsReadOnly="False" ValueType="System.Int32">12</Property> <Property Name="ModifiedSinceLastDataDump" IsReadOnly="False" ValueType="System.Boolean">False</Property> <Property Name="Load" IsReadOnly="False" ValueType="System.Single">0</Property> <Property Name="RPM" IsReadOnly="False" ValueType="System.Single">140.962</Property> <Property Name="Value" IsReadOnly="False" ValueType="System.Single">-1.1E-20</Property> <Property Name="SampleID" IsReadOnly="False" ValueType="System.Int32">-626794</Property> <Property Name="Timestamp_as_String" IsReadOnly="True" ValueType="System.String">8/18/2018 2:05:33 PM</Property> <Property Name="Timestamp_as_UInt" IsReadOnly="False" ValueType="System.UInt32">1534619133</Property> <Property Name="Timestamp" IsReadOnly="False" ValueType="System.DateTime">8/18/2018 2:05:33 PM</Property> <Property Name="StorageFlag" IsReadOnly="False" ValueType="Enum" EnumType="Emerson.CSI.DataImport.MHM.TrendDataStorageType" EnumValue="2">RPM_And_Overall</Property> <Property Name="Parents" IsReadOnly="False" IsList="True" ListType="List<string>" ValueType="Array" ArrayType="System.String" Count="5">System.Collections.Generic.List`1[System.String]<Data>Database=phmhmdb4ts;C:\RBMdbsrv\CustData\4ts_online_1807.rbm;-99|Area=4TS;-494|Equipment=4THTS;-712|MeasurementPoint=D39;-780|DataCollectionSet=Normal Collection Dryer Rolls;-783</Data></Property> </Entity> </Entities> I tried switching to the XML UDF but was alittle lost in how to use it. I am particularly interested in the ParameterNames and ParameterValues.
×
×
  • Create New...