Parsing XML files

Started by PxPlus, June 15, 2018, 11:21:09 AM

Previous topic - Next topic

PxPlus

While there are many ways to parse XML files, we generally recommend *obj/XML to parse, build, and modify XML.  It's documentation with examples can be found at: https://manual.pvxplus.com/page/utilities/obj_xml.htm

It's primary method/function set_xml(xml$) takes XML input and parses it into a node tree that you can then walk through and process.  You can also create a tree yourself using the various methods/function found in this object or make changes to and existing XML tree.  To get the resultant XML use the method get_xml$() to have it generate the XML for you.

Here is a sample program using this object:

open (1,isz=-1)"xml.txt"
read record (1,siz=1000000)R$ ! Read full file assuming < 1MB
close (1)
!
oXml=new("*obj/xml" for program)
if oXml'set_xml(R$)<>1 then print "Bad XML"; stop
!
oBatch=oXml'Find_Node("batch")
!
oAcct=0
while oBatch ! >> Account loop
oAcct=oBatch'Find_Node("account",oAcct)
if oAcct=0 then break
print "Client:",oAcct'Find_Node("cust_name")'value$
!
oInvoice=0
while oAcct ! >> Invoice loop
oInvoice=oAcct'Find_Node("invoice",oInvoice)
if oInvoice=0 then break
print "  Invoice:",oInvoice'Find_Node("invoice_number")'value$
!
oLine=0
while oInvoice ! >> Item loop
oLine=oInvoice'Find_Node("invoice_item",oLine)
if oLine=0 then break
print "    Qty:",oLine'Find_Node("quantity")'value$,
print " of ",oLine'Find_Node("product_cd")'value$,
print " @ ",oLine'Find_Node("price")'value$
wend ! << End item loop
!
wend ! << End Invoice loop
!
wend ! << End Account loop
!
drop object oXml
end



The test XML file for the above code is attached to this post and when run it should output something like this:

-:run
Client:ABC Construction
  Invoice:1000
    Qty:10 of Wall Brackets @ 10.0000
    Qty:20 of Cover Plates @ 2.5000
  Invoice:1001
    Qty:1 of Wire Wrap @ 2.5000
Client:Boat Outfitters
  Invoice:1002
    Qty:10 of 40-Volt Lithium-ion Battery @ 150.0000