Descent XML
An XML Parser Helper Library
Loading...
Searching...
No Matches
First Tutorial: Make it Run

This tutorial assumes you already have descent_xml and libadt set up in your environment.

This program will be the basis for future tutorials.

It will:

  • initialize a token from an XML string
  • tests that the XML is a valid XML document
  • iterate the token from the beginning of the XML to the end
  • exit the program

Save it to a file called noop-example.c and compile with cc -o noop-example noop-example.c -ldescent_xmlstatic.

1#include <libadt/str.h>
2#include <descent-xml.h>
3
4typedef struct descent_xml_lex lex_t;
5
6#define str libadt_str_literal
7
8#define lex descent_xml_lex_init
9#define eof descent_xml_classifier_eof
10#define unexpected descent_xml_classifier_unexpected
11#define error descent_xml_parse_error
12#define parse descent_xml_parse_cstr
13#define valid descent_xml_validate_document
14
15static int is_end_type(lex_t token)
16{
17 return token.type == eof;
18}
19
20static int is_error_type(lex_t token)
21{
22 return token.type == unexpected
23 || token.type == error;
24}
25
26int main()
27{
28 lex_t token = lex(str("<element>Hello, world!</element>"));
29 if (!valid(token))
30 return 1;
31
32 while (!is_end_type(token)) {
33 if (is_error_type(token)) {
34 // Handle error
35 return 1;
36 }
37
38 token = parse(token, NULL, NULL, NULL);
39 }
40}
Represents a single token.
Definition lex.h:42
descent_xml_classifier_fn * type
Represents the type of token classifiered.
Definition lex.h:46

The program includes a pretty long preamble, which just removes namespacing noise from libadt and descent_xml functions and data types.

Otherwise, we've defined a few functions for convenience:

  • is_end_type checks if the token given to it reflects an end-of-file
  • is_error_type checks if the token given is of one of two error types:
    • descent_xml_classifier_unexpected means the lexer encountered a character in an unexpected location (for example, an end-of-file inside an element started with <)
    • descent_xml_parse_error means that the parser encountered an error unrelated to the document. For example, the C-string parsing interface allocates memory to copy values, which can fail.

Once you've gotten the program to compile and run, you can progress on to Second Tutorial: A Simple Printer.