ChrisBair

Help pulling data out of XML file

10 posts in this topic

I'm trying to read some data from an XML file (order numbers, tracking numbers and ship date) and can't seem to get _XMLDomWrapper_.au3 to work. 

Ultimately my goal is to use the data to navigate to a web page (baseURL+order#) change a value, click a button, enter the tracking number and date and then click another button (repeated however many orders were in the XML file). I have a pretty good foundation with automating IE to do what I need (would prefer chrome but it seems the UDF for that died when google started enforcing chrome app origination) but I can't seem to get the XML down. Here is a seriously abbreviated version of the XML file with all the non-relevant nodes removed (and the tracking numbers are fake)

<?xml version="1.0" encoding="utf-8"?>
<Print xmlns="http://stamps.com/xml/namespace/2009/8/Client/BatchProcessingV1">
  <Item>
    <OrderID>5235</OrderID>
    <TrackingNumber>910551169922324005344</TrackingNumber>
    <ActualMailingDate>2015-08-11</ActualMailingDate>
  </Item>
  <Item>
    <OrderID>5236</OrderID>
    <TrackingNumber>94055118992354208016</TrackingNumber>
    <ActualMailingDate>2015-08-11</ActualMailingDate>
  </Item>
  <Item>
    <OrderID>5237</OrderID>
    <TrackingNumber>94055158992354208016</TrackingNumber>
    <ActualMailingDate>2015-08-11</ActualMailingDate>
  </Item>
</Print>

 

Share this post


Link to post
Share on other sites



It's polite to post what you have tried instead of us second guessing how you misunderstood the UDF.


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 04/09/2015

Share this post


Link to post
Share on other sites

Basing off other examples I found on this forum, the best I came up with was 

$sXmlFile = "c:\xmlfile.xml"
$oOXml = _XMLFileOpen ($sXmlFile)
$cnt = _XMLGetNodeCount ('//Print/Item/*', "")

Dim $aAttrName[1], $aAttrValue[1]

For $i = 0 To $cnt - 1
    $ret = _XMLGetAllAttribIndex ("//Print/Item/OrderID/*", $aAttrName, $aAttrValue, "", $i)
    If IsArray($aAttrName) Then
        _ArrayDisplay($aAttrName, "Attrib Names")
        _ArrayDisplay($aAttrValue, "Attrib Values")
    Else
        MsgBox(0, "Error", "No items found.")
        Exit
    EndIf
Next

doesn't return anything.

 

Earlier I tried

$xmlarray = _XML_ElementsToArry("c:\xmlfile.xml")

Func _XML_ElementsToArry ( $sXMLFilePath )
    Local $i = 1
    Local $aRetAry[1]
    $aRetAry[0] = 0
    Local $xmldoc = ObjCreate( 'Microsoft.XMLDOM' )
    If Not IsObj($xmldoc) Then
        SetError ( 1 )
        Return -1
    EndIf
    $xmldoc.async = False
    $xmldoc.load ( $sXMLFilePath )
    For $x In $xmldoc.documentElement.childNodes
        $aRetAry[0] = $aRetAry[0] + 1
        ReDim $aRetAry[$aRetAry[0]+1]
        $aRetAry[$i] = $x.NodeName
        $i = $i + 1
    Next
    Return $aRetAry
EndFunc


_ArrayDisplay($xmlarray, "2D display")

but that just gives me the first level node names ("Item" x15)

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

This is because you have:

<Print xmlns="http://stamps.com/xml/namespace/2009/8/Client/BatchProcessingV1">

instead:

<Print>

 

Try this 

Local $cnt
;~ $cnt = _XMLGetNodeCount($oXml, '//Print/Item', "")
$cnt = _XMLGetNodeCount($oXml, "//*[name()='Item']")
....
$ret = _XMLGetAllAttribIndex($oXml, "//*[name()='Item']/OrderID/*", $aAttrName, $aAttrValue, "", $i)

 

 

Edited by mLipok

Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest begining - comunication with GitHub REST API *
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 API *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF *

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 * Best coding practices * 

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) * 

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: 2017-06-04

Share this post


Link to post
Share on other sites

Here you go:

; just demonstrating through a temp file
#include <File.au3>
$sTempFile = "Temp.xml"
$string = "<?xml version=""1.0"" encoding=""utf-8""?>" & @CRLF & _
"<Print xmlns=""http://stamps.com/xml/namespace/2009/8/Client/BatchProcessingV1"">" & @CRLF & _
  "<Item>" & @CRLF & _
    "<OrderID>5235</OrderID>" & @CRLF & _
    "<TrackingNumber>910551169922324005344</TrackingNumber>" & @CRLF & _
    "<ActualMailingDate>2015-08-11</ActualMailingDate>" & @CRLF & _
  "</Item>" & @CRLF & _
  "<Item>" & @CRLF & _
    "<OrderID>5236</OrderID>" & @CRLF & _
    "<TrackingNumber>94055118992354208016</TrackingNumber>" & @CRLF & _
    "<ActualMailingDate>2015-08-11</ActualMailingDate>" & @CRLF & _
  "</Item>" & @CRLF & _
  "<Item>" & @CRLF & _
    "<OrderID>5237</OrderID>" & @CRLF & _
    "<TrackingNumber>94055158992354208016</TrackingNumber>" & @CRLF & _
    "<ActualMailingDate>2015-08-11</ActualMailingDate>" & @CRLF & _
  "</Item>" & @CRLF & _
"</Print>"
_FileCreate($sTempFile)
FileWrite($sTempFile,$string)

; real stuff here
Local $oXML = ObjCreate("Microsoft.XMLDOM")
$oXML.load($sTempFile)

$oItems = $oXML.SelectNodes("//Print/Item")         ; or //Item
For $oItem In $oItems

    $oOrderID = $oItem.SelectSingleNode("./OrderID")
    $oTrackingNum = $oItem.SelectSingleNode("./TrackingNumber")
    $oActualDate = $oItem.SelectSingleNode("./ActualMailingDate")
    ConsoleWrite("$oOrderID=[" & $oOrderID.text & "]; $oTrackingNum=[" & $oTrackingNum.text & "]; $oActualDate=[" & $oActualDate.text & "]" & @CRLF)
Next

Output:

$oOrderID=[5235]; $oTrackingNum=[910551169922324005344]; $oActualDate=[2015-08-11]
$oOrderID=[5236]; $oTrackingNum=[94055118992354208016]; $oActualDate=[2015-08-11]
$oOrderID=[5237]; $oTrackingNum=[94055158992354208016]; $oActualDate=[2015-08-11]


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.

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

Why it works with:

Local $oXML = ObjCreate("Microsoft.XMLDOM")
; or
Local $oXML = ObjCreate("Msxml2.DOMDocument.3.0")

and not working with:

Local $oXML = ObjCreate("Msxml2.DOMDocument.4.0")
; or
Local $oXML = ObjCreate("Msxml2.DOMDocument.6.0")

 

EDIT:

https://msdn.microsoft.com/en-us/library/ms754523(v=vs.85).aspx

Note Note

Previously, in MSXML 3.0 and earlier versions, the selection object created by calling the selectNodes method would gradually calculate the node-set. If the DOM tree was modified, while the selectNodes call was still actively iterating its contents, the behavior could potentially change the nodes that were selected or returned. In MSXML 6., the node-set result is fully calculated at the time of selection. This ensures that the iteration is simple and predictable. In rare instances, this change might impact legacy code written to accommodate previous behavior.

 

Edited by mLipok

Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest begining - comunication with GitHub REST API *
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 API *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF *

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 * Best coding practices * 

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) * 

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: 2017-06-04

Share this post


Link to post
Share on other sites

Here you go: 

; just demonstrating through a temp file

Like the OP I'm trying to read data from an XML file and your post really helped me. However I am still having trouble accessing a text field. I have modified the code to include typical but fictitious examples of the text fields in the XML. I have hard coded ItemSize and ItemColour strings in the extraction code and it would help greatly if you could show me how to adjust the first two lines in the loop such that the actual text fields are extracted from the sample.

; just demonstrating through a temp file
#include <File.au3>
$sTempFile = "Temp.xml"
$string = "<?xml version=""1.0"" encoding=""utf-8""?>" & @CRLF & _
"<Print xmlns=""http://stamps.com/xml/namespace/2009/8/Client/BatchProcessingV1"">" & @CRLF & _
  "<Item ItemSize=""XL"" ItemColour=""White"">" & @CRLF & _
    "<OrderID>5235</OrderID>" & @CRLF & _
    "<TrackingNumber>910551169922324005344</TrackingNumber>" & @CRLF & _
    "<ActualMailingDate>2015-08-11</ActualMailingDate>" & @CRLF & _
  "</Item>" & @CRLF & _
  "<Item ItemSize=""SM"" ItemColour=""Green"">" & @CRLF & _
    "<OrderID>5236</OrderID>" & @CRLF & _
    "<TrackingNumber>94055118992354208016</TrackingNumber>" & @CRLF & _
    "<ActualMailingDate>2015-08-11</ActualMailingDate>" & @CRLF & _
  "</Item>" & @CRLF & _
  "<Item ItemSize=""XL"" ItemColour=""Blue"">" & @CRLF & _
    "<OrderID>5237</OrderID>" & @CRLF & _
    "<TrackingNumber>94055158992354208016</TrackingNumber>" & @CRLF & _
    "<ActualMailingDate>2015-08-11</ActualMailingDate>" & @CRLF & _
  "</Item>" & @CRLF & _
"</Print>"
_FileCreate($sTempFile)
FileWrite($sTempFile,$string)

; real stuff here
Local $oXML = ObjCreate("Microsoft.XMLDOM")
$oXML.load($sTempFile)

$oItems = $oXML.SelectNodes("//Print/Item")         ; or //Item
For $oItem In $oItems
    $sItemSize = "XL" ;$sItemSize = $oItem.UnknownMethod("ItemSize")
    $sItemColour = "Blue" ;$sItemColour = $oItem.UnknownMethod("ItemColour")
    $oOrderID = $oItem.SelectSingleNode("./OrderID")
    $oTrackingNum = $oItem.SelectSingleNode("./TrackingNumber")
    $oActualDate = $oItem.SelectSingleNode("./ActualMailingDate")
    ;ConsoleWrite("$oOrderID=[" & $oOrderID.text & "]; $oTrackingNum=[" & $oTrackingNum.text & "]; $oActualDate=[" & $oActualDate.text & "]" & @CRLF)
    ConsoleWrite("ItemSize=[" & $sItemSize & "]; ItemColour=[" & $sItemColour & "]; $oOrderID=[" & $oOrderID.text & "]; $oTrackingNum=[" & $oTrackingNum.text & "]; $oActualDate=[" & $oActualDate.text & "]" & @CRLF)
Next

 


Phil Seakins

Share this post


Link to post
Share on other sites
Local $oXML = ObjCreate("Microsoft.XMLDOM")
$oXML.load($sTempFile)
ConsoleWrite($oXml.xml)
$oItems = $oXML.SelectNodes("//Print/Item")         ; or //Item
For $oItem In $oItems

    $oOrderID = $oItem.SelectSingleNode("./OrderID")
    $sItemSize = $oItem.getattribute("ItemSize")
    $sItemColour = $oItem.getattribute("ItemColour")
    $oTrackingNum = $oItem.SelectSingleNode("./TrackingNumber")
    $oActualDate = $oItem.SelectSingleNode("./ActualMailingDate")
    ;ConsoleWrite("$oOrderID=[" & $oOrderID.text & "]; $oTrackingNum=[" & $oTrackingNum.text & "]; $oActualDate=[" & $oActualDate.text & "]" & @CRLF)
    ConsoleWrite("ItemSize=[" & $sItemSize & "]; ItemColour=[" & $sItemColour & "]; $oOrderID=[" & $oOrderID.text & "]; $oTrackingNum=[" & $oTrackingNum.text & "]; $oActualDate=[" & $oActualDate.text & "]" & @CRLF)
Next

 


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.

Share this post


Link to post
Share on other sites

Wow what a champion! I've been wrestling with this for weeks, I go to lunch and when I get back you've given me the complete answer. Funnily enough I have https://msdn.microsoft.com/en-us/library/ms761380(v=vs.85).aspx  MSDN getAttribute Method already open in one of my browser tabs. The answer was right in front of me and I couldn't see it.

I really appreciate your rapid and helpful responses. Thanks heaps.


Phil Seakins

Share this post


Link to post
Share on other sites

After jdelaney put me on the right path, I tried methods I had seen while researching and found that it is possible to get the same result as post #5 with a For-Next loop. Individual elements\attributes of the required node can be directly addressed. The OP may be interested in looking at this modified loop giving the same output.

ConsoleWrite('$oItems.length = [' & $oItems.length & ']' & @CRLF)
For  $i = 0 To $oItems.length - 1
  $sOrderID = $oItems($i).SelectSingleNode("OrderID").text
  $sTrackingNum = $oItems($i).SelectSingleNode("TrackingNumber").text
  $sActualDate = $oItems($i).SelectSingleNode("ActualMailingDate").text
  ConsoleWrite("$sOrderID=[" & $sOrderID & "]; $sTrackingNum=[" & $sTrackingNum & "]; $sActualDate=[" & $sActualDate & "]" & @CRLF)
Next

Phil Seakins

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