W3C

RDF Interfaces

A set of basic primitives and a low-level API for working with RDF data

W3C Working Group Note 05 July 2012

This version:
http://www.w3.org/TR/2012/NOTE-rdf-interfaces-20120705/
Latest published version:
http://www.w3.org/TR/rdf-interfaces/
Latest editor's draft:
http://www.w3.org/2010/02/rdfa/sources/rdf-interfaces/
Previous version:
http://www.w3.org/TR/2011/WD-rdf-interfaces-20110510/
Editors:
Nathan Rixham, Invited Expert
Manu Sporny, Digital Bazaar, Inc.
Benjamin Adrian, German Research Center for Artificial Intelligence GmbH
Authors:
Nathan Rixham, Invited Expert
Manu Sporny, Digital Bazaar, Inc.
Mark Birbeck, Sidewinder Labs
Ivan Herman, W3C
Benjamin Adrian, German Research Center for Artificial Intelligence GmbH

Abstract

This document is not finished. Due to the lack of time, the RDF Web Applications Working Group was unable to complete work on this document before the end of their charter. At the time of publication of this document, it was not known whether W3C will continue this work on the Recommendation track in another Working Group. While a significant amount of design work went into this document, at present there are no known implementations of the specification. A number of design issues have not been completely resolved. Developers wishing to implement this API should be aware of incomplete nature of the specification.

The RDF Interfaces Specification defines a set of standardized interfaces for working with RDF data in a programming environment. This specification outlines three distinct sets of interfaces:

Status of This Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document was published by the RDF Web Applications Working Group as a Note. I f you wish to make comments regarding this document, please send them to public-rdfa@w3.org (subscribe, archives). All feedback is welcome.

Publication as a Working Group Note does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

Table of Contents

1. Introduction

This section is non-normative.

This document is a detailed specification for the RDF Interfaces. The document is primarily intended for the following audiences:

This is a preliminary specification and is therefore fairly unstable. Implementers are warned that the interfaces in this document may change on a frequent basis until the specification reaches W3C Last Call status.

If you are not familiar with RDF, you should read about the Resource Description Framework (RDF) [RDF-CONCEPTS] before reading this document.

Readers who are not familiar with the Terse RDF Triple Language [TURTLE] may want to read the specification in order to understand the short-hand RDF notation used in some of the examples.

This document uses the Web Interface Definition Language [WEBIDL] to specify all language bindings. If you intend to implement any part of the RDF Interfaces you should be familiar with the Web IDL language [WEBIDL].

Examples may contain references to existing vocabularies and use abbreviations in CURIEs and source code. The following is a list of all vocabularies and their abbreviations, as used in this document:

1.1 Conformance

As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.

The key words must, must not, required, should, should not, recommended, may, and optional in this specification are to be interpreted as described in [RFC2119].

Conformance requirements phrased as algorithms or specific steps may be implemented in any manner, so long as the end result is equivalent. In particular, the algorithms defined in this specification are intended to be easy to follow, and not intended to be performant.

User agents may impose implementation-specific limits on otherwise unconstrained inputs, e.g. to prevent denial of service attacks, to guard against running out of memory, or to work around platform-specific limitations.

Implementations that use ECMAScript or Java to implement the Interfaces defined in this specification must implement them in a manner consistent with the respective ECMAScript or Java Bindings defined in the Web IDL specification, as this specification uses that specification's terminology. [WEBIDL]

Implementations that use any other language to implement the Interfaces defined in this specification that do not have bindings defined in the Web IDL specification should attempt to map the Interfaces as closely as possible to the implementation language's native mechanisms and datatypes. Developers are encouraged to work with other developers who are providing the RDF Interfaces in the same langauge to ensure that implementations are modular and easily exchangable.

2. RDF Concept Interfaces

The RDF Concept Interfaces in this specification provide a low level API for working with RDF data.

The concepts described in this specification are more generalized than those defined by the RDF Data Model [RDF-CONCEPTS]. Whilst this may appear to be a mismatch, the RDF specification is intended to define a notation for transmitting data on the Web, however this specification defines a set of interfaces for working with that data, behind the public interface, where more generalized notions of Triples are often required by libraries and modules.

2.1 Overview

The core interfaces for working with RDF defined by this specification are as follows:

Graph
A Graph holds a set of Triples.
Triple

A Triple consists of three components:

  • the subject, which is an RDFNode
  • the predicate, which is an RDFNode
  • the object, which is an RDFNode

Triples are the basic data structure utilized by RDF to express statements.

Throughout documentation and examples, Triples are conventionally written in the order subject, predicate, object - for example:

<http://example.org/hp> rdfs:label "Harry Potter" .

NamedNode

A node identified by an IRI. For example: <http://example.org/people#mark>

Note: IRIs are defined by International Resource Identifier [IRI] and are compatible with RDF URI references as defined by RDF Concepts [RDF-CONCEPTS].

BlankNode

A blank node is a reference to an unnamed resource (one for which an IRI is not known), and may be used in a Triple as a unique reference to that unnamed resource.

BlankNodes are typically stringified by prepending "_:" to a unique value, for instance _:b142 or _:me, this stringified form is referred to as a "blank node identifier".

Note: Blank node identifiers are only guaranteed to be unique within a single instance of a single Graph, the string form of a blank node identifier cannot be relied upon over time; that is to say, two graphs may hold different blank nodes which both stringify as "_:b2", and the same blank node within the same graph may have the stringified identifier "_:x23" in one instance and "_:ui9x" in another.

Literal

A literal value, optionally combined with a language attribute and/or a datatype attribute.

Literals are used for untyped string data, plain text in a natural language, or values which have a specific datatype. For example:

  • "Harry Potter and the Half-Blood Prince"@en is plain text expressed in the English language.
  • "7"^^xsd:integer is a value with a datatype of xsd:integer.

In addition to the above, this specification provides an RDFNode interface, which is implemented by those interfaces which can occupy a position in a Triple.

Implementers may provide additional types and/or a deeper type or class hierarchy so long as it includes these basic types.

2.2 Data Structures

2.2.1 Triples

The Triple interface represents an RDF Triple. The stringification of a Triple results in an N-Triples representation as defined in [RDF-TESTCASES].

Implementors should be aware that a UTF-8 version of N-Triples may be defined by the RDF WG, as such the definition/implementation of the toString method may change.

[NoInterfaceObject]
interface Triple {
    readonly attribute RDFNode subject;
    readonly attribute RDFNode predicate;
    readonly attribute RDFNode object;
    stringifier DOMString toString ();
    boolean               equals (Triple otherTriple);
};
Attributes
object of type RDFNode, readonly
The object associated with the Triple.
predicate of type RDFNode, readonly
The predicate associated with the Triple.
subject of type RDFNode, readonly
The subject associated with the Triple.
Methods
equals
Returns true if otherTriple is equivalent to this triple.
ParameterTypeNullableOptionalDescription
otherTripleTripleThe Triple to test for equivalence with this Triple.
Return type: boolean
toString
Converts this triple into a string in N-Triples notation.
No parameters.

2.2.2 Graphs

A Graph holds a set of one or more Triples.

[NoInterfaceObject]
interface Graph {
    readonly attribute unsigned long          length;
    Graph            add (Triple triple);
    Graph            remove (Triple triple);
    Graph            removeMatches (any? subject, any? predicate, any? object);
    sequence<Triple> toArray ();
    boolean          some (TripleFilter callback);
    boolean          every (TripleFilter callback);
    Graph            filter (TripleFilter filter);
    void             forEach (TripleCallback callback);
    Graph            match (any? subject, any? predicate, any? object, optional unsigned long limit);
    Graph            merge (Graph graph);
    Graph            addAll (Graph graph);
    readonly attribute sequence<TripleAction> actions;
    Graph            addAction (TripleAction action, optional boolean run);
};
Attributes
actions of type sequence<TripleAction>, readonly
An array of actions to run when a Triple is added to the graph, each new triple is passed to the run method of each TripleAction in the array.
length of type unsigned long, readonly
A non-negative integer that specifies the number of Triples in the set.
Methods
add
Adds the specified Triple to the graph. This method returns the graph instance it was called on.
ParameterTypeNullableOptionalDescription
tripleTripleThe Triple to add. Graphs must not contain duplicate triples.
Return type: Graph
addAction
Adds a new TripleAction to the array of actions, if the run argument is specified as true then each Triple in the Graph must be passed to the TripleAction before this method returns.
ParameterTypeNullableOptionalDescription
actionTripleActionThe TripleAction to add.
runbooleanA boolean flag specifying whether all triples in the graph should immediately be tried by the action.
Return type: Graph
addAll

Imports the graph in to this graph. This method returns the graph instance it was called on.

This method differes from Graph.merge in that it adds all triples from graph to the current instance, rather than combining the two graphs to create a new instance.

ParameterTypeNullableOptionalDescription
graphGraphThe Graph to import in to this graph, the import must not produce any duplicates.
Return type: Graph
every

Universal quantification method, tests whether every Triple in the Graph passes the test implemented by the provided TripleFilter.

This method will return boolean false when the first Triple is found that does not pass the test.

Note: this method is aligned with Array.prototype.every() in ECMAScript-262.

ParameterTypeNullableOptionalDescription
callbackTripleFilterThe TripleFilter to test each Triple in the Graph against.
Return type: boolean
filter

Creates a new Graph with all the Triples which pass the test implemented by the provided TripleFilter.

Note: this method is aligned with Array.prototype.filter() in ECMAScript-262.

ParameterTypeNullableOptionalDescription
filterTripleFilterThe TripleFilter to test each Triple in the Graph against.
Return type: Graph
forEach

Executes the provided TripleCallback once on each Triple in the Graph.

Note: this method is aligned with Array.prototype.forEach() in ECMAScript-262.

ParameterTypeNullableOptionalDescription
callbackTripleCallbackThe TripleCallback to execute for each Triple.
Return type: void
match

This method returns a new Graph which is comprised of all those triples in the current instance which match the given arguments, that is, for each triple in this graph, it is included in the output graph, if:

  • calling triple.subject.equals with the specified subject as an argument returns true, or the subject argument is null, AND
  • calling triple.predicate.equals with the specified predicate as an argument returns true, or the predicate argument is null, AND
  • calling triple.object.equals with the specified object as an argument returns true, or the object argument is null

This method implements AND functionality, so only triples matching all of the given non-null arguments will be included in the result.

Note, this method always returns a new Graph, even if that Graph contains no Triples.

Note, Graphs represent Sets of Triples, the order is arbitrary, so this method may result in differing results when called repeatedly with a limit.

ParameterTypeNullableOptionalDescription
subjectanyThe subject value to match against, may be null.
predicateanyThe predicate value to match against, may be null.
objectanyThe object value to match against, may be null.
limitunsigned longAn optional limit to the amount of triples returned, if 0 is passed or the argument is set to null then all matching triples will be contained in the resulting graph.
Return type: Graph
merge
Returns a new Graph which is a concatenation of this graph and the graph given as an argument.
ParameterTypeNullableOptionalDescription
graphGraphThe Graph to concatenate with this graph, the resulting Graph must not contain any duplicates.
Return type: Graph
remove
Removes the specified Triple from the graph. This method returns the graph instance it was called on.
ParameterTypeNullableOptionalDescription
tripleTripleThe Triple to remove.
Return type: Graph
removeMatches

This method removes those triples in the current instance which match the given arguments, that is, for each triple in this graph, it is removed, if:

  • calling triple.subject.equals with the specified subject as an argument returns true, or the subject argument is null, AND
  • calling triple.predicate.equals with the specified predicate as an argument returns true, or the predicate argument is null, AND
  • calling triple.object.equals with the specified object as an argument returns true, or the object argument is null
ParameterTypeNullableOptionalDescription
subjectanyThe subject value to match against, may be null.
predicateanyThe predicate value to match against, may be null.
objectanyThe object value to match against, may be null.
Return type: Graph
some

Existential quantification method, tests whether some Triple in the Graph passes the test implemented by the provided TripleFilter.

This method will return boolean true when the first Triple is found that passes the test.

Note: this method is aligned with Array.prototype.some() in ECMAScript-262.

ParameterTypeNullableOptionalDescription
callbackTripleFilterThe TripleFilter to test each Triple in the Graph against.
Return type: boolean
toArray

Returns the set of Triples within the Graph as a host language native sequence, for example an Array in ECMAScript-262.

Note: a sequence in [WEBIDL] is passed by value, not by reference.

Note: the order of the Triples within the returned sequence is arbitrary, since a Graph is an unordered set.

No parameters.
Return type: sequence<Triple>

2.3 Basic Node Types

2.3.1 Nodes

RDFNode is the base class of NamedNode, BlankNode, and Literal.

[NoInterfaceObject]
interface RDFNode {
    readonly attribute any       nominalValue;
    readonly attribute DOMString interfaceName;
    DOMString toString ();
    any       valueOf ();
    DOMString toNT ();
    boolean   equals (any tocompare);
};
Attributes
interfaceName of type DOMString, readonly

Provides access to the string name of the current interface, normally one of "NamedNode", "BlankNode" or "Literal".

This method serves to disambiguate instances of RDFNode which are otherwise identical, such as NamedNode and BlankNode.

nominalValue of type any, readonly

The nominalValue of an RDFNode is refined by each interface which extends RDFNode.

Methods
equals

If tocompare is an instance of RDFNode then this method returns true if an only if all attributes on the two interfaces are equivalent.

If tocompare is NOT an instance of RDFNode then the it must be compared against the result of calling toValue on this node.

You cannot simply test two RDF Nodes for equivalence using general language constructs such as ==.

ParameterTypeNullableOptionalDescription
tocompareanyThe value to test for equivalence with this node.
Return type: boolean
toNT

Returns the N-Triples representation of the RDFNode as defined by [RDF-TESTCASES].

No parameters.
Return type: DOMString
toString

The stringification of an RDFNode is defined as follows, if the interfaceName is

  • NamedNode then return the stringified nominalValue.
  • BlankNode then prepend "_:" to the stringified value and return the result.
  • Literal then return the stringified nominalValue.
No parameters.
Return type: DOMString
valueOf

This method provides access to the implementations host environment native value for this RDFNode, if the interfaceName is

  • NamedNode or BlankNode then return the stringified nominalValue.
  • Literal then return the language native value for this node where supported, or the stringified nominalValue if the datatype of the Literal is unknown or the value is out of the range supported. See the definition of Literal for further guidance.
No parameters.
Return type: any

2.3.2 Named Nodes

A node identified by an IRI. IRIs are defined by International Resource Identifier [IRI].

[NoInterfaceObject]
interface NamedNode : RDFNode {
    readonly attribute any nominalValue;
};
Attributes
nominalValue of type any, readonly
The IRI identifier of the node.

2.3.3 Blank Nodes

A BlankNode is a reference to an unnamed resource (one for which an IRI is not known), and may be used in a Triple as a unique reference to that unnamed resource.

BlankNodes are stringified by prepending "_:" to a unique value, for instance _:b142 or _:me, this stringified form is referred to as a "blank node identifier".

[NoInterfaceObject]
interface BlankNode : RDFNode {
    readonly attribute any nominalValue;
};
Attributes
nominalValue of type any, readonly

The temporary identifier of the BlankNode, the nominalValue may be of any type, so long as it is unique and can be stringified, for instance a number or a string.

The nominalValue must not be relied upon in any way between two separate processing runs of the same document, or two instances of Graph containing "the same" triples.

Developers and authors must not assume that the nominalValue of a BlankNode will remain the same between two processing runs. BlankNode nominalValues are only valid for the most recent processing run on the document. BlankNodes nominalValues will often be generated differently by different processors.

Implementers must ensure that BlankNode nominalValues are unique within the current environment, two BlankNodes are considered equal if, and only if, their nominalValues are strictly equal.

2.3.4 Literals

Literals represent values such as numbers, dates and strings in RDF data. A Literal is comprised of three attributes:

  • a lexical representation of the nominalValue
  • an optional language represented by a string token
  • an optional datatype specified by a NamedNode

Literals representing plain text in a natural language may have a language attribute specified by a text string token, as specified in [BCP47], normalized to lowercase (e.g., 'en', 'fr', 'en-gb'). They may also have a datatype attribute such as xsd:string.

The RDF Working Group is currently looking at the handling of "Plain Literals", with regards to datatypes, further guidance may result in changes to this specification.

Literals representing values with a specific datatype, such as the integer 72, may have a datatype attribute specified in the form of a NamedNode (e.g., <http://www.w3.org/2001/XMLSchema#integer>).

Literals often represent values for which the host environment of an RDF Interface implementation has a corresponding native value, this value can be accessed by the valueOf method of the Literal interface.

Implementations must provide native value type conversion, via the valueOf method, for the following XML Schema datatypes:

  • xsd:string
  • xsd:boolean
  • xsd:dateTime
  • xsd:date
  • xsd:time
  • xsd:int
  • xsd:double
  • xsd:float
  • xsd:decimal
  • xsd:positiveInteger
  • xsd:integer
  • xsd:nonPositiveInteger
  • xsd:negativeInteger
  • xsd:long
  • xsd:int
  • xsd:short
  • xsd:byte
  • xsd:nonNegativeInteger
  • xsd:unsignedLong
  • xsd:unsignedInt
  • xsd:unsignedShort
  • xsd:unsignedByte

When a Literal contains both a datatype and a language, and the serialization or stringification does not support a lexical representation of both attributes, language should take precedence.

RDF specifies that Literal equality is based on the lexical representation of values rather than the value space, for this reason the Literals "100"^^xsd:double and "1e2"^^xsd:double are not considered equal.

[NoInterfaceObject]
interface Literal : RDFNode {
    readonly attribute DOMString  nominalValue;
    readonly attribute DOMString? language;
    readonly attribute NamedNode? datatype;
    any valueOf ();
};
Attributes
datatype of type NamedNode, readonly, nullable
An optional datatype identified by a NamedNode.
language of type DOMString, readonly, nullable
An optional language string as defined in [BCP47], normalized to lowercase.
nominalValue of type DOMString, readonly
The lexical representation of the Literals value.
Methods
valueOf

This method provides access to a corresponding host environment specific native value, where one exists.

If the datatype identifier of the Literal is not known by the implementation, or the value is outside of the range handled by the corresponding native type, then valueOf must return the DOMString lexical representation of the nominalValue.

No parameters.
Return type: any

The chart below provides a datatype map for the XSD datatypes which must be supported.

Datatype Map:
Specified Datatype IDL ECMAScript
xsd:string DOMString string
xsd:boolean boolean boolean
xsd:dateTime - Date
xsd:date - Date
xsd:time - Date
xsd:int long number
xsd:double double number
xsd:float float number
xsd:decimal double number
xsd:positiveInteger long number
xsd:integer long number
xsd:nonPositiveInteger long number
xsd:negativeInteger long number
xsd:long long number
xsd:int long number
xsd:short short number
xsd:byte short number
xsd:nonNegativeInteger unsigned long number
xsd:unsignedLong unsigned long number
xsd:unsignedInt unsigned long number
xsd:unsignedShort unsigned short number
xsd:unsignedByte unsigned short number
xsd:positiveInteger unsigned long number

Implementations must convert xsd:boolean values to native booleans rather than Boolean Objects to limit unexpected behaviour.

2.4 Additional Interfaces

2.4.1 Triple Filters

The TripleFilter is a callable interface which is used to implement Triple tests, a response of true means that the test has been passed.

When used with the filter method of the Graph interface a response of true indicates the Triple should be included in the output set.

[NoInterfaceObject, Callback]
interface TripleFilter {
    boolean test (Triple triple);
};
Methods
test
A callable function that returns true if the input Triple passes the test this function implements.
ParameterTypeNullableOptionalDescription
tripleTripleThe triple to test against the filter.
Return type: boolean
Example Filters

The following shows an example set of common TripleFilters exposed on a filter attribute of RDFEnvironment:

// basic filters
rdf.filters = {
  s: function(s) { return function(t) { return t.subject.equals(s); }; },
  p: function(p) { return function(t) { return t.predicate.equals(p); }; },
  o: function(o) { return function(t) { return t.object.equals(o); }; },
  sp: function(s,p) { return function(t) { return t.subject.equals(s) && t.predicate.equals(p); }; },
  so: function(s,o) { return function(t) { return t.subject.equals(s) && t.object.equals(o); }; },
  po: function(p,o) { return function(t) { return t.predicate.equals(p) && t.object.equals(o); }; },
  spo: function(s,p,o) { return function(t) { return t.subject.equals(s) && t.predicate.equals(p) && t.object.equals(o); }; },
  describes: function(v) { return function(t) { return t.subject.equals(v) || t.object.equals(v); }; },
  type: function(o) {
    var type = rdf.resolve("rdf:type"); 
    return function(t) { return t.predicate.equals(type) && t.object.equals(o); };
  }
};

// example basic usage - find all triples with an subject or object of "http://example.org/bob#me"
var results = graph.filter( rdf.filters.describes("http://example.org/bob#me") );

// example advanced usage
// find the descriptions of all foaf:People in a graph and display a summary of them.
var displayPerson = function(graph) {
  // code to display the description of a person
};
// filter the graph to find all subjects with an "rdf:type" of "foaf:Person"
var filter = rdf.filters.type( rdf.resolve("foaf:Person");
results = graph.filter( filter );
results.forEach( function(t) {
  // iterate over the results, creating a filtered graph for each subject found
  // and pass that graph to a display function
  displayPerson( graph.filter( rdf.filters.s(t.subject) );
});

2.4.2 Triple Callbacks

The TripleCallback is a callable interface which is used to implement a function which can be called on a Triple.

This interface is typically used with the forEach method of the Graph interface.

[NoInterfaceObject, Callback]
interface TripleCallback {
    void run (Triple triple, Graph graph);
};
Methods
run
A callable function which can be executed on a Triple.
ParameterTypeNullableOptionalDescription
tripleTripleThe triple to be used.
graphGraphThe graph which contains the triple.
Return type: void

2.4.3 Triple Actions

TripleAction is an interface which combines the functionality of TripleFilter and TripleCallback, given a test and an action, the run method will execute the action if, and only if, it passes the test.

[NoInterfaceObject]
interface TripleAction {
    attribute TripleFilter   test;
    attribute TripleCallback action;
    void run (Triple triple, Graph graph);
};
Attributes
action of type TripleCallback
The action to call on triple which successfully pass the test.
test of type TripleFilter
An instance of TripleFilter used to test whether the action should be executed on a specific Triple.
Methods
run
This method will run the specified action on the specified Triple if it passes the test.
ParameterTypeNullableOptionalDescription
tripleTripleThe triple to be tried.
graphGraphThe graph which contains the triple.
Return type: void

3. RDF Environment Interfaces

3.1 Overview

The RDF Environment Interfaces provide all basic functionality needed to work with RDF data in a programming environment, and within specific contexts, for instance within a Parser, Serializer or Data Store.

3.2 Terms, Prefixes and Profiles

Within a programming context, and within various RDF serializations, it is increasingly important to be able to simplify access to properties and refer to full IRIs by using CURIEs or Terms.

In order to accomplish this a Profile of Prefix and Term mappings is needed.

This specification includes the definition of three Interfaces which serve to address these needs:

3.2.1 Prefix Maps

[NoInterfaceObject]
interface PrefixMap {
    omittable getter DOMString get (DOMString prefix);
    omittable setter void      set (DOMString prefix, DOMString iri);
    omittable deleter void     remove (DOMString prefix);
    DOMString                  resolve (DOMString curie);
    DOMString                  shrink (DOMString iri);
    void                       setDefault (DOMString iri);
    PrefixMap                  addAll (PrefixMap prefixes, optional boolean override);
};
Methods
addAll

This method returns the instance on which it was called.

ParameterTypeNullableOptionalDescription
prefixesPrefixMapThe PrefixMap to import.
overridebooleanIf true then conflicting prefixes will be overridden by those specified on the PrefixMap being imported, by default imported prefixes augment the existing set.
Return type: PrefixMap
get
ParameterTypeNullableOptionalDescription
prefixDOMStringThe prefix must not contain any whitespace
remove
ParameterTypeNullableOptionalDescription
prefixDOMStringThe prefix must contain any whitespace
resolve

Given a valid CURIE for which a prefix is known (for example "rdfs:label"), this method will return the resulting IRI (for example "http://www.w3.org/2000/01/rdf-schema#label")

If the prefix is not known then this method will return null.

ParameterTypeNullableOptionalDescription
curieDOMStringThe CURIE to resolve.
Return type: DOMString
set
ParameterTypeNullableOptionalDescription
prefixDOMStringThe prefix must not contain any whitespace
iriDOMStringAn IRI, as defined by [IRI]
setDefault
ParameterTypeNullableOptionalDescription
iriDOMStringThe iri to be used when resolving CURIEs without a prefix, for example ":this".
Return type: void
shrink
Given an IRI for which a prefix is known (for example "http://www.w3.org/2000/01/rdf-schema#label") this method returns a CURIE (for example "rdfs:label"), if no prefix is known the original IRI is returned.
ParameterTypeNullableOptionalDescription
iriDOMStringThe IRI to shrink to a CURIE
Return type: DOMString

Example

This example illustrates how PrefixMap can be used to resolve known CURIEs to IRIs, shrink IRIs in to CURIEs, and how to specify and use a default prefix.

// create a new prefix mapping for the prefix "rdfs"
prefixes.rdfs = "http://www.w3.org/2000/01/rdf-schema#";

// resolve a known CURIE
prefixes.resolve("rdfs:label"); // "http://www.w3.org/2000/01/rdf-schema#label"

// shrink an IRI for a known CURIE in to a CURIE
prefixes.shrink("http://www.w3.org/2000/01/rdf-schema#label"); // "rdfs:label"

// attempt to resolve a CURIE with an empty prefix
prefixes.resolve(":me");  // ":me"

// set the default prefix and attempt to resolve a CURIE with an empty prefix
prefixes.setDefault("http://example.org/bob#");
prefixes.resolve(":me");  // "http://example.org/bob#me"

3.2.2 Term Maps

[NoInterfaceObject]
interface TermMap {
    omittable getter DOMString get (DOMString term);
    omittable setter void      set (DOMString term, DOMString iri);
    omittable deleter void     remove (DOMString term);
    DOMString                  resolve (DOMString term);
    DOMString                  shrink (DOMString iri);
    void                       setDefault (DOMString iri);
    TermmMap                   addAll (TermMap terms, optional boolean override);
};
Methods
addAll

This method returns the instance on which it was called.

ParameterTypeNullableOptionalDescription
termsTermMapThe TermMap to import.
overridebooleanIf true then conflicting terms will be overridden by those specified on the TermMap being imported, by default imported terms augment the existing set.
Return type: TermmMap
get
ParameterTypeNullableOptionalDescription
termDOMStringThe term must not contain any whitespace or the : (single-colon) character
remove
ParameterTypeNullableOptionalDescription
termDOMStringThe term must not contain any whitespace or the : (single-colon) character
resolve

Given a valid term for which an IRI is known (for example "label"), this method will return the resulting IRI (for example "http://www.w3.org/2000/01/rdf-schema#label").

If no term is known and a default has been set, the IRI is obtained by concatenating the term and the default iri.

If no term is known and no default is set, then this method returns null.

ParameterTypeNullableOptionalDescription
termDOMStringThe term to resolve.
Return type: DOMString
set
ParameterTypeNullableOptionalDescription
termDOMStringThe term must not contain any whitespace or the : (single-colon) character
iriDOMStringAn IRI, as defined by [IRI]
setDefault
ParameterTypeNullableOptionalDescription
iriDOMStringThe default iri to be used when an term cannot be resolved, the resulting IRI is obtained by concatenating this iri with the term being resolved.
Return type: void
shrink
Given an IRI for which an term is known (for example "http://www.w3.org/2000/01/rdf-schema#label") this method returns a term (for example "label"), if no term is known the original IRI is returned.
ParameterTypeNullableOptionalDescription
iriDOMStringThe IRI to shrink to an term
Return type: DOMString

Example

This example illustrates how TermMap can be used to resolve known terms to IRIs, shrink IRIs for known terms in to terms, and how to specify and use a default vocabulary for unknown terms.

// create a new term mapping for the term "member" 
terms.member = "http://www.w3.org/ns/org#member";

// resolve a known term to an IRI
terms.resolve("member"); // "http://www.w3.org/ns/org#member"

// shrink an IRI for a known term to a term
terms.shrink("http://www.w3.org/ns/org#member"); // "member"

// attempt to resolve an unknown term
terms.resolve("label"); // null

// set the default term vocabulary and then attempt to resolve an unknown term
terms.setDefault("http://www.w3.org/2000/01/rdf-schema#");
terms.resolve("label"); // "http://www.w3.org/2000/01/rdf-schema#label"

3.2.3 Profiles

Profiles provide an easy to use context for negotiating between CURIEs, Terms and IRIs.

[NoInterfaceObject]
interface Profile {
    readonly attribute PrefixMap prefixes;
    readonly attribute TermMap   terms;
    DOMString resolve (DOMString toresolve);
    void      setDefaultVocabulary (DOMString iri);
    void      setDefaultPrefix (DOMString iri);
    void      setTerm (DOMString term, DOMString iri);
    void      setPrefix (DOMString prefix, DOMString iri);
    Profile   importProfile (Profile profile, optional boolean override);
};
Attributes
prefixes of type PrefixMap, readonly
An instance of PrefixMap
terms of type TermMap, readonly
An instance of TermMap
Methods
importProfile

This method functions the same as calling prefixes.addAll(profile.prefixes, override) and terms.addAll(profile.terms, override), and allows easy updating and merging of different profiles, such as those exposed by parsers.

This method returns the instance on which it was called.

ParameterTypeNullableOptionalDescription
profileProfileThe Profile to import.
overridebooleanIf true then conflicting terms and prefixes will be overridden by those specified on the Profile being imported, by default imported terms and prefixes augment the existing set.
Return type: Profile
resolve

Given an Term or CURIE this method will return an IRI, or null if it cannot be resolved.

If toresolve contains a : (colon) then this method returns the result of calling prefixes.resolve(toresolve)

otherwise this method returns the result of calling terms.resolve(toresolve)

ParameterTypeNullableOptionalDescription
toresolveDOMStringA string Term or CURIE.
Return type: DOMString
setDefaultPrefix
This method sets the default prefix for use when resolving CURIEs without a prefix, for example ":me", it is identical to calling the setDefault method on prefixes.
ParameterTypeNullableOptionalDescription
iriDOMStringThe IRI to use as the default prefix.
Return type: void
setDefaultVocabulary
This method sets the default vocabulary for use when resolving unknown terms, it is identical to calling the setDefault method on terms.
ParameterTypeNullableOptionalDescription
iriDOMStringThe IRI to use as the default vocabulary.
Return type: void
setPrefix
This method associates an IRI with a prefix, it is identical to calling the set method on prefixes.
ParameterTypeNullableOptionalDescription
prefixDOMStringThe prefix to set, must not contain any whitespace.
iriDOMStringThe IRI to associate with the prefix.
Return type: void
setTerm
This method associates an IRI with a term, it is identical to calling the set method on term.
ParameterTypeNullableOptionalDescription
termDOMStringThe term to set, must not contain any whitespace or the : (single-colon) character
iriDOMStringThe IRI to associate with the term.
Return type: void

3.3 High level API

The RDF Interfaces are primarily intended to enable interoperability between RDF libraries and extensions, and for usage by advanced users. Implementations are encouraged to provide their own sets of abstracted interfaces and methods tailored to the use-cases they are addressing.

Implementors are encouraged to share implementations of various interfaces defined in this specification, offering specialized or highly optimized implementations of interfaces, for instance rigourously tested parsers and serializers for specific RDF serializations, or highly optimized Graph interfaces.

Methods to instantiate the basic interfaces required to work with RDF data in a programming environment, are all exposed by a single interface, as described in the following section.

3.3.1 RDF Environment

The RDF Environment is an interface which exposes a high level API for working with RDF in a programming environment.

The RDF Environment interface extends Profile and provides the default context for working with CURIEs, Terms and IRIs, implementations are encouraged to offer rich prefix maps by default, and must instantiate the environment with the following prefixes defined:

Prefix IRI
owl http://www.w3.org/2002/07/owl#
rdf http://www.w3.org/1999/02/22-rdf-syntax-ns#
rdfs http://www.w3.org/2000/01/rdf-schema#
rdfa http://www.w3.org/ns/rdfa#
xhv http://www.w3.org/1999/xhtml/vocab#
xml http://www.w3.org/XML/1998/namespace
xsd http://www.w3.org/2001/XMLSchema#

This interface also exposes all methods required to create instances of TermMaps, PrefixMaps, Profiles and all the Concept Interfaces.

Implementations of the RDFEnvironment must expose all the methods defined on this interface, as defined by this specification.

Future RDF Interface extensions and modules may supplement this interface with methods and attributes which expose the functionality they define, in a manner consistent with this API.

interface RDFEnvironment : Profile {
    BlankNode    createBlankNode ();
    NamedNode    createNamedNode (DOMString value);
    Literal      createLiteral (DOMString value, optional DOMString? language, optional NamedNode? datatype);
    Triple       createTriple (RDFNode subject, RDFNode predicate, RDFNode object);
    Graph        createGraph (optional []Triple triples);
    TripleAction createAction (TripleFilter test, TripleCallback action);
    Profile      createProfile (optional boolean empty);
    TermMap      createTermMap (optional boolean empty);
    PrefixMap    createPrefixMap (optional boolean empty);
};
Methods
createAction
Creates a TripleAction given a TripleFilter test and a TripleCallback action.
ParameterTypeNullableOptionalDescription
testTripleFilterThe TripleFilter to test the Triple against.
actionTripleCallbackThe action to run should the Triple being tried pass the test.
Return type: TripleAction
createBlankNode
Creates a new BlankNode.
No parameters.
Return type: BlankNode
createGraph
Creates a new Graph, an optional array of Triples to include within the graph may be specified, this allows easy transition between native arrays and Graphs and is the counterpart for the toArray method of the Graph interface.
ParameterTypeNullableOptionalDescription
triples[]TripleAn optional array of Triples to be added to the Graph as it is created.
Return type: Graph
createLiteral
Creates a Literal given a value, an optional language and/or an optional datatype.
ParameterTypeNullableOptionalDescription
valueDOMString

The value to be represented by the Literal, the value must be a lexical representation of the value.

languageDOMStringThe language that is associated with the Literal encoded according to the rules outlined in [BCP47].
datatypeNamedNodeThe datatype of the Literal.
Return type: Literal
createNamedNode
Creates a NamedNode identified by the given IRI.
ParameterTypeNullableOptionalDescription
valueDOMStringAn IRI, CURIE or TERM.
Return type: NamedNode
createPrefixMap
ParameterTypeNullableOptionalDescription
emptybooleanIf true is specified then an empty PrefixMap will be returned, by default the PrefixMap returned will be populated with prefixes replicating those of the current RDF environment.
Return type: PrefixMap
createProfile
ParameterTypeNullableOptionalDescription
emptybooleanIf true is specified then a profile with an empty TermMap and PrefixMap will be returned, by default the Profile returned will contain populated term and prefix maps replicating those of the current RDF environment.
Return type: Profile
createTermMap
ParameterTypeNullableOptionalDescription
emptybooleanIf true is specified then an empty TermMap will be returned, by default the TermMap returned will be populated with terms replicating those of the current RDF environment.
Return type: TermMap
createTriple
Creates a Triple given a subject, predicate and object. If any incoming value does not match the requirements listed below, a Null value must be returned by this method.
ParameterTypeNullableOptionalDescription
subjectRDFNodeThe subject value of the Triple.
predicateRDFNodeThe predicate value of the Triple.
objectRDFNodeThe object value of the Triple.
Return type: Triple

4. RDF Data Interfaces

4.1 Overview

The RDF Data Interfaces are modular, standalone interfaces which can be implemented by RDF Libraries and API extensions to enable interoperability.

Developers and Specification authors are encouraged to use these interfaces when defining functionality within one of the realms covered by these interfaces.

Parser and Serializer implementors should provide relevant parse, process or serialize methods on the RDF Environment interface for their implementations. For example a Turtle parser should augment RDFEnvironment with parseTurtle and processTurtle methods which accept a String toparse argument, whilst an RDFa parser should augment RDFEnvironment with a parseRDFa method which accepts a Document argument.

4.2 Parsing and Serializing Data

4.2.1 Data Parsers

The DataParser is a generic RDF document parser which can be used to either parse the triples serialized within an RDF document in to a Graph, or to process an RDF document by passing each triple found to a TripleCallback for processing.

[NoInterfaceObject, Constructor, Constructor(in RDFEnvironment rdf)]
interface DataParser {
    readonly attribute Graph processorGraph;
    boolean parse (any toparse, ParserCallback? callback, optional DOMString base, optional TripleFilter filter, optional Graph graph);
    boolean process (any toparse, ProcessorCallback callback, optional DOMString base, optional TripleFilter filter);
};
Attributes
processorGraph of type Graph, readonly
An optional Graph produced by RDF Parsers containing additional parsing information and errors.
Methods
parse

Parses the triples serialized within an input RDF document in to a Graph, then executes a given ParserCallback on the populated Graph.

If a TripleFilter is passed to the parser, then each Triple found in the document will only be added to the output Graph if it passes the test implemented by the TripleFilter.

By default a new Graph is provided, however users may optionally specify a Graph to which the parsed triples will be added. This allows users to provide a custom or persistent Graph implementation, or to automatically merge the triples from several documents in to a single Graph.

A boolean response is given indicating if the parse was successful or not.

ParameterTypeNullableOptionalDescription
toparseanyThe document to parse, the type of argument required may further be constrained by implementations of this interface, for instance an RDFa parser may require an instance of Document, whilst a Turtle parser may require a String.
callbackParserCallbackThe ParserCallback to execute once the parse has completed, the ParserCallback will be passed a single argument which is the propulated Graph.
baseDOMStringAn optional base to be used by the parser when resolving relative IRI references.
filterTripleFilterAn optional TripleFilter to test each Triple against before adding to the output Graph, only those triples successfully passing the test will be added to the output graph.
graphGraphAn optional Graph to add the parsed triples to, if no Graph is provided then a new, empty, Graph will be used.
Return type: boolean
process

Parses the triples serialized within an input RDF document and passes each (non filtered) Triple found to a TripleCallback, this interface allows RDF documents to be processed by SAX-like parsers whilst maintaining a minimal memory footprint.

If a TripleFilter is passed to the parser, then each Triple found in the document will only be passed to the TripleCallback if it passes the test implmented by the filter.

ParameterTypeNullableOptionalDescription
toparseanyThe document to parse, the type of argument required may further be constrained by implementations of this interface, for instance an RDFa parser may require an instance of Document, whilst a Turtle parser may require a String.
callbackProcessorCallbackThe ProcessorCallback to execute on each (non-filtered) Triple found by the parser.
baseDOMStringAn optional base to be used by the parser when resolving relative IRI references.
filterTripleFilterAn optional TripleFilter to test each Triple against before adding to the output Graph, only those triples successfully passing the test will be added to the output graph.
Return type: boolean
Examples

Example of basic and advanced DataParser.parse usage:

// basic usage
turtle.parse(doc, function(graph) {
  // work with graph here ..
});

// advanced usage, retrieve a graph containing only those triples
// with a subject of "<http://example.org/bob#me>"
var filter = function(t) { // create a filter
  return t.subject.equals( "http://example.org/bob#me" );
};
var parsercb = function(graph) {
  // work with graph here
};
turtle.parse(doc, parsercb, "http://example.org/bob", filter);

Example of basic and advanced DataParser.process usage:

// basic usage
turtle.process(doc, function(t) {
  // work with triples here ..
});

// advanced usage, process only those triples with a predicate of rdf:type
var filter = function(t) { // create a filter
  return t.predicate.equals( rdf.resolve("rdf:type") );
};
var processor = function(t) {
  // work with triples here
};
turtle.process(doc, processor, "http://example.org/bob", filter);

4.2.2 Data Serializers

The DataSerializer is a generic interface implemented by Graph serializers.

Implementations of this interface may further constrain the return type, for instance an RDFa serializer may return an instance of Document, whilst a Turtle serializer may return a String.

[NoInterfaceObject, Constructor, Constructor(in RDFEnvironment rdf)]
interface DataSerializer {
    any serialize (Graph graph);
};
Methods
serialize
A method, which when called will serialize the given Graph and return the resulting serialization.
ParameterTypeNullableOptionalDescription
graphGraph
Return type: any

4.2.3 Additional Interfaces

The ParserCallback interface is used by the parse method of the DataParser interface.

[NoInterfaceObject Callback]
interface ParserCallback {
    void run (Graph graph);
};
Methods
run
A function to be executed on a Graph produced by a parse operation on an RDF Document.
ParameterTypeNullableOptionalDescription
graphGraph
Return type: void

The ProcessorCallback interface is used by the process method of the DataParser interface.

[NoInterfaceObject Callback]
interface ProcessorCallback {
    void run (Triple triple);
};
Methods
run
A function to be executed on a Triple produced by a process operation on an RDF Document.
ParameterTypeNullableOptionalDescription
tripleTriple
Return type: void

A. Acknowledgements

At the time of publication, the members of the RDF Web Application Working Group were:

B. References

B.1 Normative references

[BCP47]
A. Phillips, M. Davis. Tags for Identifying Languages September 2009. IETF Best Current Practice. URL: http://tools.ietf.org/rfc/bcp/bcp47.txt
[IRI]
M. Duerst, M. Suignard. Internationalized Resource Identifiers (IRI). January 2005. Internet RFC 3987. URL: http://www.ietf.org/rfc/rfc3987.txt
[RDF-CONCEPTS]
Graham Klyne; Jeremy J. Carroll. Resource Description Framework (RDF): Concepts and Abstract Syntax. 10 February 2004. W3C Recommendation. URL: http://www.w3.org/TR/2004/REC-rdf-concepts-20040210
[RDF-TESTCASES]
Jan Grant; Dave Beckett. RDF Test Cases. 10 February 2004. W3C Recommendation. URL: http://www.w3.org/TR/2004/REC-rdf-testcases-20040210
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt
[WEBIDL]
Cameron McCormack. Web IDL. 27 September 2011. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2011/WD-WebIDL-20110927/

B.2 Informative references

[TURTLE]
David Beckett, Tim Berners-Lee. Turtle: Terse RDF Triple Language. January 2008. W3C Team Submission. URL: http://www.w3.org/TeamSubmission/turtle/