XPact documentation: XML parsing library for C and C#

How to build XPact and use it from your own program. The full C header is include/xpact.h; the design is described in the repository's design overview.

Overview

XPact has two layers:

LayerLanguageUse it when
The parser (XP_PARSER)EiffelYour program is written in Eiffel
The C library (xpact.dll + xpact.h)Eiffel, compiled to CYour program is written in C, C++, C# or anything that can call a C library

There are two builds of the library: production (xpact.dll, contracts off, faster) and assertions (xpact_assertions.dll, every contract checked, for testing).

Installation

You need Windows x64, EiffelStudio 25.x and Visual Studio's C++ tools (MSVC).

git clone https://github.com/andersoxie/xpact.git
cd xpact
git checkout incremental-test

# Build the C library (both builds)
.\scripts\build_native_eiffel.ps1 -BuildTier Production
.\scripts\build_native_eiffel.ps1 -BuildTier Assertions

# Result:
#   build\native-eiffel\xpact.dll   xpact.lib
#   build\native-eiffel\xpact_assertions.dll   xpact_assertions.lib

Link your program with xpact.lib, include include/xpact.h, and ship xpact.dll next to your executable. See windows-release.md for a packaged release.

C API

The library follows the Expat API, so Expat's documentation also applies. The functions most programs need:

FunctionPurpose
XML_ParserCreate(encoding)Create a parser. encoding may be NULL (detect from the document).
XML_ParserCreateNS(encoding, sep)Create a parser with namespace processing; names become uri + sep + local.
XML_SetElementHandler / XML_SetStartElementHandler / XML_SetEndElementHandlerCalled for each start and end tag (name, attributes).
XML_SetCharacterDataHandlerCalled for text. Text may arrive in several pieces.
XML_SetCommentHandler, XML_SetProcessingInstructionHandlerComments and <?target data?>.
XML_SetDefaultHandlerEverything that has no other handler, as raw text.
XML_SetExternalEntityRefHandlerLets your program load external entities. Without it, nothing outside the document is read.
XML_SetUserDataA pointer passed to every handler.
XML_Parse(parser, s, len, isFinal)Parse the next piece of the document. Call it as often as you like; the last call has isFinal = 1.
XML_StopParser / XML_ResumeParserStop or suspend parsing from inside a handler.
XML_GetErrorCode, XML_ErrorStringWhy parsing failed: an Expat-compatible code and its text.
XML_GetCurrentLineNumber, XML_GetCurrentColumnNumber, XML_GetCurrentByteIndexWhere the parser is (or where the error is).
XML_ParserReset, XML_ParserFreeReuse or release a parser.
XML_ExpatVersionThe API version string (XPact reports the Expat version it follows).

Coverage of the whole Expat API: libexpat-api-compatibility.md.

Example: C

#include <stdio.h>
#include <string.h>
#include "xpact.h"

static void XMLCALL on_start(void *data, const XML_Char *name, const XML_Char **atts) {
    int *depth = data;
    printf("%*s<%s>\n", 2 * (*depth)++, "", name);
}

static void XMLCALL on_end(void *data, const XML_Char *name) {
    int *depth = data;
    --*depth;
}

int main(void) {
    const char *xml = "<catalog><book id=\"1\"/><book id=\"2\"/></catalog>";
    int depth = 0;
    XML_Parser p = XML_ParserCreate(NULL);
    XML_SetUserData(p, &depth);
    XML_SetElementHandler(p, on_start, on_end);

    if (XML_Parse(p, xml, (int)strlen(xml), 1) == XML_STATUS_ERROR) {
        fprintf(stderr, "error %d: %s at line %lu, column %lu\n",
                XML_GetErrorCode(p), XML_ErrorString(XML_GetErrorCode(p)),
                XML_GetCurrentLineNumber(p), XML_GetCurrentColumnNumber(p));
    }
    XML_ParserFree(p);
    return 0;
}

Build: cl /I include example.c build\native-eiffel\xpact.lib

Example: C#

The website itself calls XPact from C# with P/Invoke (Native.cs):

[DllImport("xpact", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr XML_ParserCreate(byte* encoding);

[DllImport("xpact", CallingConvention = CallingConvention.Cdecl)]
static extern int XML_Parse(IntPtr parser, byte* s, int len, int isFinal);

IntPtr p = XML_ParserCreate(null);
fixed (byte* bytes = document)
    ok = XML_Parse(p, bytes, document.Length, 1) == 1;

Website REST API

The validator on this site is a thin client of a small REST API you can call yourself:

# Raw XML body
curl --data-binary @example.xml -H "Content-Type: application/xml" \
     "http://localhost:5080/api/validate?build=production"

# JSON
curl -H "Content-Type: application/json" \
     -d '{"xml":"<a><b></a>","build":"assertions","chunkSize":1}' \
     http://localhost:5080/api/validate

Response fields, limits and error codes: website/docs/api.md.

Supported features

  • ✅ XML 1.0, fifth edition: well-formedness checking (non-validating)
  • ✅ Encodings: UTF-8, UTF-16 (with BOM), ISO-8859-1, US-ASCII
  • ✅ Internal DTD subset: entity and attribute-list declarations, default attributes
  • ✅ Namespaces (XML_ParserCreateNS)
  • ✅ External entities and DTDs, only when your program loads them (XML_SetExternalEntityRefHandler)
  • ✅ Incremental parsing: the document may arrive in pieces of any size
  • ⬜ XML 1.1: documents are processed as XML 1.0 (as XML 1.0 §2.8 requires)
  • ⬜ DTD validation (validity constraints): not done; XPact is non-validating, like Expat

Known limitations

Open issues, with their tracking numbers. Each one has a report in the repository.

LimitationEffectIssue
Input declared ISO-8859-1 and fed in pieces is decoded again on every call1 MB in 1 KB pieces: 46 s (Expat 0.2 s). UTF-8 and UTF-16 input in pieces is linear#272
Threads take turnsSeveral threads, each with its own parser, are safe since #274, but their calls run one at a time (Expat parses in parallel)#304
SpeedA median of 18 times slower than native Expat 2.8.1 through the same C API (see Benchmarks)#275
Entities nested more than 32 levels deepRejected as "syntax error"; Expat accepts them#293
Billion-laughs documentsStopped with Expat's error, but after about 1.5 s (Expat about 0.1 s)#211
Some error codes differ from ExpatSame accept/reject verdict, a different code in 14 W3C cases#170
Error columnsThe column of an error can differ from Expat's#171
]]> split across pieces; some CDATA events before a UTF-8 errorEvents can differ from Expat when the document is fed in pieces#176, #123
Raw carriage returns to the default handlerThe default handler gets normalised line ends; Expat passes the raw CR#126