Jump to content
rudi

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!

Share this post


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.

Share this post


Link to post
Share on other sites

I'm on my vacation/holidays 


Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest beginning - communication with GitHub REST API Forum Rules *
Include Dependency Tree (Tool for analyzing script relations)
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  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 *

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 * 

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

PDF Related:https://www.autoitscript.com/forum/topic/177368-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 *

"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: 2020-09-20

Share this post


Link to post
Share on other sites
Posted (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.
 

#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 by TheXman
Tidy up the script / Added test.xml file

Share this post


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!

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

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • 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.
    • By macran
      I want to generating a XML file (test.xml) like as follow:
      <?xml version="1.0" encoding="GBK"?>
      <!DOCTYPE SCHEMA SYSTEM "HGWSPZJK.dtd">  ;I can not generate this line
      <SCHEMA CRC="HGWSPZ201808_9131011571786229XM_CRC.XML" SSSQ="201808" CHSNAME="HGWSDKQD" NAME="HGWSPZ">

      <TAXPAYER CJRMC="sigmagroup" CJRDM="9131011571786229XM" CJLX="DKZK" RECORDCOUNT="411" SBRQ="2018-08-31" NSRMC="sigmagroup" SWSBH="9131011571786229XM">

      <Records>
      <Record BZ="" JKKADM="2244" JKKAMC="shanghai" SE="5907.82" TFRQ="2018-08-23" FPHM="224420181000752586-L02"/>
      <Record BZ="" JKKADM="2244" JKKAMC="shanghai" SE="4742.4" TFRQ="2018-08-21" FPHM="224420181000743016-L01"/>
      <Record BZ="" JKKADM="2244" JKKAMC="shanghai" SE="18720" TFRQ="2018-08-14" FPHM="224420181000719215-L01"/>
      </Records>
      </TAXPAYER>
      </SCHEMA>
      I use XML.UDF  
      Local $oXMLile=_XML_CreateFile(@ScriptDir&"\test.xml","",True) 
      but there is no function CreateDocumentType 
      It is no effort even I test use 
      Local $doct=$oXMLfile.CreateDocumentType("SCHEMA", null, "HGWSPZJK.dtd", null)
            $oXmlfile.appendChild($doct)
      pls help me thanks.
       
       
       
       
       
       
×
×
  • Create New...