Parsing an XML File

You can use three main op-codes to parse an XML file with C$XML: CXML-PARSE-FILE, CXML-OPEN-FILE, and CXML-NEW-PARSER. Each has a slightly different function, as described below. Choose the one that best suits your needs.

Op-code Description
CXML-PARSE-FILE Opens and parses the specified file
CXML-OPEN-FILE Opens the specified file, so you can parse individual records
CXML-NEW-PARSER     Opens a new, empty XML file
Note: C$XML can parse local or remote files–even files located on the Internet. You simply specify the server, IP address, or URL in the pathname. You cannot write to URLs, however.

If you prefer, you can parse an XML file directly without opening a file with the CXML-PARSE-STRING op-code. Examples for using these op-codes appear in the following paragraphs.

Opening and parsing a file

To open and read an entire XML file, use the CXML-PARSE-FILE op-code. Once a file is parsed, all its elements are immediately retrievable. Parsing entire files can take some time, depending on the size of the file. Use this option when you plan to work extensively with the whole file or when the file is small.

For instance:

call "C$XML" using CXML-PARSE-FILE "" 
move return-code to parser-handle

Opening a file, parsing individual records

To simply open the file, but not parse it, use the CXML-OPEN-FILE op-code. With the file open, you can then parse individual records using the CXML-PARSE-NEXT-RECORD op-code. For instance:

move return-code to parser-handle 
CALL "C$XML" using CXML-PARSE-NEXT-RECORD parser-handle 
move return-code to record-handle

This option is more efficient than parsing entire files, but you must remember to parse the record before you try to retrieve its elements.

Creating a new parser

To create a new XML file, use the CXML-NEW-PARSER op-code. An empty file is opened, into which you can add children, siblings, attributes, and comments as described in the topic Adding Modifying or Deleting Data. Note that the file is not "created" until you write to the file using the CXML-WRITE-FILE op-code.

Parsing an XML string directly

If you get XML text from another source and need to parse it, you can parse the string directly using the CXML-PARSE-STRING op-code. You don't have to write the data to a file, then parse the file. You simply specify the string directly in the call. For example:

call "C$XML" using CXML-PARSE-STRING, 
"<?xml version=""1.0""?><group1><subgroup1><item1>data</item1></subgroup1></group1>". 
move return-code to parse-handle. 

Then you can use the return code elsewhere in your program.