rudi Posted August 20, 2020 Posted August 20, 2020 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): expandcollapse popup<?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" Present in XML or not (true) if present then return the values for... type (mobile) givenname (Max) familyname (Mustermann) company (Schlosserei Mustermann GmbH) 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!
Developers Jos Posted August 22, 2020 Developers Posted August 22, 2020 The shown information is not real I hope? Jos SciTE4AutoIt3 Full installer Download page - Beta files Read before posting How to post scriptsource Forum etiquette Forum Rules Live for the present, Dream of the future, Learn from the past.
Jury Posted August 22, 2020 Posted August 22, 2020 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.
mLipok Posted August 22, 2020 Posted August 22, 2020 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 * IE on Windows 11 * How to ask ChatGPT for AutoIt Code * 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 API * ErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 * 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 TaskScheduler * IE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related: * How to get reference to PDF object embeded in IE * IE on Windows 11 * 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 stuff * OnHungApp handler * Avoid "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" , 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: 2023-04-24
TheXman Posted August 22, 2020 Posted August 22, 2020 (edited) 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. expandcollapse popup#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 test.xml Edited March 18, 2021 by TheXman Tidy up the script / Added test.xml file CryptoNG UDF: Cryptography API: Next Gen jq UDF: Powerful and Flexible JSON Processor | jqPlayground: An Interactive JSON Processor Xml2Json UDF: Transform XML to JSON | HttpApi UDF: HTTP Server API | Roku Remote: Example Script About Me How To Ask Good Questions On Technical And Scientific Forums (Detailed) | How to Ask Good Technical Questions (Brief) "Any fool can know. The point is to understand." -Albert Einstein "If you think you're a big fish, it's probably because you only swim in small ponds." ~TheXman
rudi Posted August 23, 2020 Author Posted August 23, 2020 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!
rudi Posted January 7, 2021 Author Posted January 7, 2021 @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: phone number types might show up more than once, e.g. if someone has two private or to work mobile phones. 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!
TheXman Posted January 7, 2021 Posted January 7, 2021 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. I usually don't help people that don't appreciate it. Maybe my example in the post below may help you. Good luck. CryptoNG UDF: Cryptography API: Next Gen jq UDF: Powerful and Flexible JSON Processor | jqPlayground: An Interactive JSON Processor Xml2Json UDF: Transform XML to JSON | HttpApi UDF: HTTP Server API | Roku Remote: Example Script About Me How To Ask Good Questions On Technical And Scientific Forums (Detailed) | How to Ask Good Technical Questions (Brief) "Any fool can know. The point is to understand." -Albert Einstein "If you think you're a big fish, it's probably because you only swim in small ponds." ~TheXman
rudi Posted January 7, 2021 Author Posted January 7, 2021 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!
rudi Posted January 7, 2021 Author Posted January 7, 2021 Thanks for your example, still not getting to my propably really simple goal, to see a list of "child nodes" -- expandcollapse popup#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 ; |... 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!
rudi Posted January 15, 2021 Author Posted January 15, 2021 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!
TheXman Posted January 15, 2021 Posted January 15, 2021 (edited) 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 January 15, 2021 by TheXman CryptoNG UDF: Cryptography API: Next Gen jq UDF: Powerful and Flexible JSON Processor | jqPlayground: An Interactive JSON Processor Xml2Json UDF: Transform XML to JSON | HttpApi UDF: HTTP Server API | Roku Remote: Example Script About Me How To Ask Good Questions On Technical And Scientific Forums (Detailed) | How to Ask Good Technical Questions (Brief) "Any fool can know. The point is to understand." -Albert Einstein "If you think you're a big fish, it's probably because you only swim in small ponds." ~TheXman
rudi Posted January 20, 2021 Author Posted January 20, 2021 @TheXman thanks for your additional input. I'll appreciate it and will hopefully come back with my fixed and functional lines. CU, Rudi. Earth is flat, pigs can fly, and Nuclear Power is SAFE!
jdelaney Posted January 21, 2021 Posted January 21, 2021 (edited) 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 January 21, 2021 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.
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now