GetXMLField

XML
Aptilis 2

GetXMLField(PARSED_xml_in_a_string, path)

GetXMLField will extract a field from a piece of XML.

Note that you cannot extract directly from raw XML.
You must first parse the XML with the parseXML command.

The path is the form name1:[index].name2[:index]... etc.
See the examples to see what this mean. If indexes are not specified, then they're assumed to be 0, so the path will bring back the first element that it matches.

Indexes start at 0.

Return Value:
The field specified or an empty string if not found.

All the examples will load a file called 'test.xml' that contains the following:

<container technology="tj">
<n_individuals>4</n_individuals>
<individual>
<name>Teebo</name>
<favfood>Pizza</favfood>
</individual>

<individual>
<name>Mickey</name>
<favfood>Cheese</favfood>
</individual>

<individual>
<name>Donald</name>
<favfood>Bread Crumbs</favfood>
</individual>

<individual>
<name>Casimir</name>
<favfood>Gloobeboolga</favfood>
</individual>

</container>

Example 1:
Simple loading, parsing and field extraction

xml = loadFile("test.xml") $

// We always reset _errno, as loadFile may have set it.
_errno = "" $
pxml = parseXML(xml$) $

field = getXMLField(pxml$, "CONTAINER.INDIVIDUAL.NAME") $

print(field$)
Result:
Teebo

Example 2:
Same thing (simplified) but with error checking code.

xml = loadFile("test.xml") $

// We always reset _errno, as loadFile may have set it.
_errno = "" $
pxml = parseXML(xml$) $

// Here's how to test for errors
if len(xml$) = 0 and len(_errno$) > 0
// We have an error!
print(_errno$)
end if
// etc...

Example 3:
Same as example 1, only now we are using an index.

xml = loadFile("test.xml") $

// We always reset _errno, as loadFile may have set it.
_errno = "" $
pxml = parseXML(xml$) $

field = getXMLField(pxml$, "CONTAINER.INDIVIDUAL:2.NAME") $

print(field$)
Result:
Donald

Example 4:
A bit more useful, we now extract all the names.
Note the use of the 'stuff' command.

xml = loadFile("test.xml") $

// We always reset _errno, as loadFile may have set it.
_errno = "" $
pxml = parseXML(xml$) $


// First we get the number of fields:
n = getXMLField(pxml$, "CONTAINER.N_INDIVIDUALS")

// Using Stuff is the easier way to build a complex key.
key = "CONTAINER.INDIVIDUAL:!(i).NAME" $
for i=0 to n - 1

// int it so as to avoid all the 000000000

i = int(i) $
field = getXMLField(pxml$, stuff(key$)$) $

print(field$, "\n")
end for
Result:
Teebo
Mickey
Donald
Casimir

See also parseXML, GetXMLTagAttributes, and stuff.