Jump to content

Searching fields within XML


 Share

Recommended Posts

I have created an app that allows me to save server names as field values and other information associated with their nodes. (example below)

<Servers>
    <ServerInfo>
        <Server_Name>MyServerName</Server_Name>
        <User>user_name</User>
        <Password>0x8534C1E508D4CF29AC17</Password>
    </ServerInfo>
</Servers

I am trying to use "_XMLNodeExists" from "_XMLDOMWrapper.au3" to search for existing server entries by field value. (Sorry if my XML terms are not quite right) I didn't quite follow how to search and I am not sure if this function can perform how I expect it to...

My attempt 

_XMLNodeExists('//Servers/ServerInfo/Server_Name/MyServerName')

Any suggestions how I might go about searching my XML file? I had thought of just searching as plain text.

Link to comment
Share on other sites

; #FUNCTION# ===================================================================
; Name ..........: _XMLNodeExists
; Description ...: Checks for the existence of a node or nodes matching the specified path
; Syntax.........: _XMLNodeExists($strXPath)
; Parameters ....: $strXPath      - Path to check for.
; Return values .: Success        - 1 or Higher , 0
;                  Failure        - 0 and @Error set to:
;                  |0 - No error.
;                  |1 - No XML object @extended = 31.
;                  |2 - Node not found.
; Author ........: Stephen Podhajecki <gehossafats a t netmdc.com>
; Modified ......:
; Remarks .......: Returns the number of nodes found (could be greater than 1)
; Related .......:
; Link ..........;
; Example .......; [yes/no]
; ==============================================================================
Func _XMLNodeExists(ByRef $objDoc, $strXPath)
    If Not IsObj($objDoc) Then
        _XMLError("No object passed to function _XMLNodeExists")
        Return SetError(1, 31, 0)
    EndIf
    Local $iCount
    Local $objNode = $objDoc.SelectNodes($strXPath)
    If IsObj($objNode) Then $iCount = $objNode.length
    $objNode = 0
    If $iCount Then Return $iCount
    Return SetError(2, 0, 0)
EndFunc   ;==>_XMLNodeExists

 

This header is not complete.

when you focus on function declaration:

.....
Func _XMLNodeExists(ByRef $objDoc, $strXPath)
.....

Then you find that you miss one parameter ;)

 

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 Codefor 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) * 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 TaskSchedulerIE 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 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: 2023-04-24

Link to comment
Share on other sites

Interesting... your version of "_XMLNodeExists" appears to be different than what I have...

; #FUNCTION# ===================================================================
; Name ..........: _XMLNodeExists
; Description ...: Checks for the existence of a node or nodes matching the specified path
; Syntax.........:  _XMLNodeExists($strXPath)
; Parameters ....: $strXPath      - Path to check for.
; Return values .: Success        - 1 or Higher , 0
;                  Failure        - 0 and @Error set to:
;                  |0 - No error.
;                  |1 - No XML object @extended = 31.
;                  |2 - Node not found.
; Author ........: Stephen Podhajecki <gehossafats a t netmdc.com>
; Modified ......:
; Remarks .......: Returns the number of nodes found (could be greater than 1)
; Related .......:
; Link ..........;
; Example .......; [yes/no]
; ==============================================================================
Func _XMLNodeExists($strXPath)
    If Not IsObj($objDoc) Then
        _XMLError("No object passed to function _XMLNodeExists")
        Return SetError(1, 31, 0)
    EndIf
    Local $objNode, $iCount
    Local $objNode = $objDoc.SelectNodes($strXPath)
    If IsObj($objNode) Then $iCount = $objNode.length
    $objNode = 0
    If $iCount Then Return $iCount
    Return SetError(2, 0, 0)
EndFunc   ;==>_XMLNodeExists

If I create a test script that only looks for the node name, it returns the number of matching nodes. My test script:

#include <_XMLDOMWrapper.au3>

$searchVal = 'MyServer'
_XMLFileOpen(@ScriptDir&"\Servers.xml")

$srchRes = _XMLNodeExists('//Servers/ServerInfo/Server_Name')

ConsoleWrite("Results: "&$srchRes&@CRLF)

This seems to return similar results as "_XMLGetNodeCount". I am looking for field value search results.

Link to comment
Share on other sites

Interesting... your version of "_XMLNodeExists" appears to be different than what I have...

I take this function snippet from: 

Global Const $_XMLUDFVER = "1.0.3.98"

But you can try to look here: XMLWrapperEx.au3 - BETA 

If I create a test script that only looks for the node name, it returns the number of matching nodes. My test script:

#include <_XMLDOMWrapper.au3>

$searchVal = 'MyServer'
_XMLFileOpen(@ScriptDir&"\Servers.xml")

$srchRes = _XMLNodeExists('//Servers/ServerInfo/Server_Name')

ConsoleWrite("Results: "&$srchRes&@CRLF)

This seems to return similar results as "_XMLGetNodeCount". I am looking for field value search results.

This is correct, as in this element:
 

<Server_Name>MyServerName</Server_Name>

"MyServerName" is value so you can not check like this:

_XMLNodeExists('//Servers/ServerInfo/Server_Name/MyServerName')

as there is no element MyServerName. 

EDIT: 

If you want to get value then you should use _XMLGetValue(...)

 

 

Edited by mLipok

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 Codefor 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) * 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 TaskSchedulerIE 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 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: 2023-04-24

Link to comment
Share on other sites

Thank you for your replies @mLipok, @jdelaney. Your suggestions gave me and an idea and reminded me of some steps I had taken in the past. Below is my initial groundwork for my solution that may be useful for others. If there are suggestions for improving my methods, let me know. :)

#include <_XMLDOMWrapper.au3>
#include <array.au3>

Local $aSrvInf = _ReadXMLFile(), $tmp

$tmp = _ArraySearch($aSrvInf,"MyServerName",0,0,0,0,1,0) ;Search for server name in column designated for server names
ConsoleWrite("Found match at "&$tmp&@CRLF) ;Show the row number the match was found at


Func _ReadXMLFile() ;Create an array with the values stored in the server information XML
Local $nodCnt, $c
If Not FileExists(@ScriptDir&"\servers.xml") Then
    ConsoleWrite("Unable to open servers.xml. Please be sure it is in the same directory as the script."&@CRLF)
    Exit
EndIf

If not _XMLFileOpen(@ScriptDir&"\servers.xml") Then
    ConsoleWrite("Error opening the 'servers.xml' file")
Else
    $nodCnt = _XMLGetNodeCount("//ServerInfo")
    If $nodCnt = -1 Then
        ConsoleWrite("There was a problem reading the servers.xml file. Please check the file."&@CRLF)
        Exit
    EndIf
    ConsoleWrite("There are "&$nodCnt&" ServerInfo nodes"&@CRLF)
    Local $aServInfo[$nodCnt][3]
    For $c = 1 to $nodCnt
        $aServInfo[$c-1][0] = _XMLGetChildText('//ServerInfo['&$c&']/Server_Name')[1]
        $aServInfo[$c-1][1] = _XMLGetChildText('//ServerInfo['&$c&']/User')[1]
        $aServInfo[$c-1][2] = _XMLGetChildText('//ServerInfo['&$c&']/Password')[1]
    Next
    _ArrayDisplay($aServInfo)
    Return($aServInfo)
EndIf

EndFunc

This searches and XML file with this format:

<Servers>
    <ServerInfo>
        <Server_Name>MyServerName</Server_Name>
        <User>user_name</User>
        <Password>0x8534C1E508D4CF29AC17</Password>
    </ServerInfo>
</Servers>

 

Link to comment
Share on other sites

I'd go this route:

#include <Array.au3>
$xml = "<Servers>" & _
"<ServerInfo><Server_Name>MyServerName1</Server_Name><User>user_name1</User><Password>0x8534C1E508D4CF29AC17a</Password></ServerInfo>" & _
"<ServerInfo><Server_Name>MyServerName2</Server_Name><User>user_name2</User><Password>0x8534C1E508D4CF29AC17b</Password></ServerInfo>" & _
"<ServerInfo><Server_Name>MyServerName3</Server_Name><User>user_name3</User><Password>0x8534C1E508D4CF29AC17b</Password></ServerInfo>" & _
"</Servers>"
Global Enum $iServerName, $iUser, $iPassword, $iUBound



Local $oXML = ObjCreate("Microsoft.XMLDOM")
$oXML.LoadXML($xml)
$oServers = $oXML.selectNodes("//ServerInfo")
Local $a
For $oServer In $oServers

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

    $a[UBound($a)-1][$iServerName] = $oServer.selectSingleNode("./Server_Name").text
    $a[UBound($a)-1][$iUser] = $oServer.selectSingleNode("./User").text
    $a[UBound($a)-1][$iPassword] = $oServer.selectSingleNode("./Password").text
Next
_ArrayDisplay($a)

 

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 comment
Share on other sites

  • 3 weeks later...

You can check it like this:

#include <AutoItConstants.au3>
#include <MsgBoxConstants.au3>

Local $oObj1 = ObjCreate("Microsoft.XMLDOM")
ObjName_FlagsValue($oObj1)

Local $oObj2 = ObjCreate("Msxml2.DOMDocument.3.0")
ObjName_FlagsValue($oObj2)

Func ObjName_FlagsValue(ByRef $oObj)
    Local $sInfo = ''

    $sInfo &= '+>' & @TAB & 'ObjName($oObj,1) {The name of the Object} =' & @CRLF & @TAB & ObjName($oObj, $OBJ_NAME) & @CRLF

    ; HELPFILE REMARKS: Not all Objects support flags 2 to 7. Always test for @error in these cases.
    $sInfo &= '+>' & @TAB & 'ObjName($oObj,2) {Description string of the Object} =' & @CRLF & @TAB & ObjName($oObj, $OBJ_STRING)
    If @error Then $sInfo &= '@error = ' & @error
    $sInfo &= @CRLF & @CRLF

    $sInfo &= '+>' & @TAB & 'ObjName($oObj,3) {The ProgID of the Object} =' & @CRLF & @TAB & ObjName($oObj, $OBJ_PROGID)
    If @error Then $sInfo &= '@error = ' & @error
    $sInfo &= @CRLF & @CRLF

    $sInfo &= '+>' & @TAB & 'ObjName($oObj,4) {The file that is associated with the object in the Registry} =' & @CRLF & @TAB & ObjName($oObj, $OBJ_FILE)
    If @error Then $sInfo &= '@error = ' & @error
    $sInfo &= @CRLF & @CRLF

    $sInfo &= '+>' & @TAB & 'ObjName($oObj,5) {Module name in which the object runs (WIN XP And above). Marshaller for non-inproc objects.} =' & @CRLF & @TAB & ObjName($oObj, $OBJ_MODULE)
    If @error Then $sInfo &= '@error = ' & @error
    $sInfo &= @CRLF & @CRLF

    $sInfo &= '+>' & @TAB & 'ObjName($oObj,6) {CLSID of the object''s coclass} =' & @CRLF & @TAB & ObjName($oObj, $OBJ_CLSID)
    If @error Then $sInfo &= '@error = ' & @error
    $sInfo &= @CRLF & @CRLF

    $sInfo &= '+>' & @TAB & 'ObjName($oObj,7) {IID of the object''s interface} =' & @CRLF & @TAB & ObjName($oObj, $OBJ_IID)
    If @error Then $sInfo &= '@error = ' & @error
    $sInfo &= @CRLF & @CRLF

    MsgBox($MB_SYSTEMMODAL, "ObjName:", $sInfo)
EndFunc   ;==>ObjName_FlagsValue

 

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 Codefor 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) * 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 TaskSchedulerIE 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 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: 2023-04-24

Link to comment
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
 Share

×
×
  • Create New...