a firstworks project
Rudiments
About Documentation Download Licensing News

Using the csvdom class

The csvdom class provides a framework for DOM parsing of CSV data. It parses a file or string of CSV-formatted data and produces a dom tree representing the data. The first row is treated as a header containing column names. Since the csvdom class creates a representation of the CSV data in memory, it should not be used to process arbitrarily large files which could exhaust system memory.

The csvdom class also provides convenience methods for accessing data. The getColumnCount() and getRecordCount() methods return the number of columns and records. The getField() method returns the value at a given record and column (by index or name).

Additional methods are available for manipulating the CSV data, including renaming, inserting, moving, and deleting columns and records, trimming fields, and upper/lower-casing column names.

The following program parses a CSV string containing a list of animals, uses the convenience methods to print each animal's data, and writes the CSV back to standard output.

#include <rudiments/csvdom.h>
#include <rudiments/domnode.h>
#include <rudiments/stdio.h>

int main(int argc, const char **argv) {

	csvdom	csv;

	// parse a csv string
	csv.parseString(
		"\"name\",\"type\",\"legs\",\"domestic\"\n"
		"\"dog\",\"mammal\",\"4\",\"yes\"\n"
		"\"eagle\",\"bird\",\"2\",\"no\"\n"
		"\"snake\",\"reptile\",\"0\",\"no\"\n");


	// access data using convenience methods
	stdoutput.printf("columns: %lld\n",csv.getColumnCount());
	stdoutput.printf("records: %lld\n\n",csv.getRecordCount());

	stdoutput.write("all animals:\n");
	for (uint64_t i=0; i<csv.getRecordCount(); i++) {

		const char	*name=csv.getField(i,"name");
		const char	*type=csv.getField(i,"type");
		const char	*legs=csv.getField(i,"legs");
		const char	*domestic=csv.getField(i,"domestic");

		stdoutput.printf("  %s (%s) - %s legs - domestic: %s\n",
						name,type,legs,domestic);
	}
	stdoutput.write('\n');


	// write the csv tree to standard output
	stdoutput.write("csv output:\n");
	csv.write();
	stdoutput.write('\n');
}
Copyright 2017 - David Muse - Contact