XmlPL By Example: A Simple Query

This example demonstrates making a simple query on an XML document. If you are familar with XPath this will be very easy.

Steps

  1. Create XML data to be queried
  2. Create main function for XML input
  3. Do the query
  4. Build & Run

1. Create XML data to be queried

Here is the XML data that will be used in this example.

<addressbook>
  <address firstname="Clark" lastname="Kent">
    <street>344 Clinton St., Apt. 3B</street>
    <city>Metropolis</city>
  </address>

  <address firstname="Sherlock" lastname="Holmes">
    <street>221B Baker Street</street>
    <city>London</city>
  </address>

  <address firstname="Homer" lastname="Simpson">
    <street>742 Evergreen Terrace</street>
    <city>Springfield</city>
  </address>
</addressbook>

2. Create main function for XML input

node[] main(document in) {
}

This demonstrates another possible main function signature. The code declares main to output a stream of XML data and read standard input as an XML document.

3. Do the query

Next we select and output the address with firstname attribute equal to "Sherlock" for output.

node[] main(document in) {
  in/addressbook/address[@firstname == "Sherlock"];
}

XPath programmers will notice a difference here. XmlPL, like C used '==' for equality and '=' for assignment unlike XPath where '=' is the equality operator. Also, notice that in is a variable reference and not a path step such as addressbook and address.

4. Build & Run

The following comands will build and run the program.

$ xmlplcc query.xml
$ ./query < addressbook.xml

This should be the output.

<?xml version="1.0" encoding="UTF-8"?>
<address firstname="Sherlock" lastname="Holmes">
    <street>221B Baker Street</street>
    <city>London</city>
  </address>

The odd indenting of the closing </address> tag is due to whitespace in the input file. You can clean up the output with a program such as tidy using the following command.

$ ./query < addressbook.xml | tidy -xml