Search code examples
c#.netdotnetrdf

Creating a base-less graph


Per the description of BaseGraph.CreateUriNode:

Generally we expect to be passed an absolute URI, while relative URIs are permitted the behaviour is less well defined. If there is a Base URI defined for the Graph then relative URIs will be automatically resolved against that Base, if the Base URI is not defined then relative URIs will be left as is. In this case issues may occur when trying to serialize the data or when accurate round tripping is required.

This seems to imply that when the base URI is not set, the URI will be stored as it is. However, all of these attempts to create it fail:

var graph = new Graph();
graph.CreateUriNode();
graph.CreateUriNode(new Uri("", UriKind.Relative));
graph.CreateUriNode(new Uri("relative", UriKind.Relative));

The first attempt fails with:

RdfParseException: 'Cannot use an Empty URI to refer to the document Base URI since there is no in-scope Base URI!'

The last two simply with:

InvalidOperationException: 'This operation is not supported for a relative URI.'

I am aware that some serialization methods may not support relative URIs, but at least Turtle does, and I want to be able to produce documents that refer to an externally-specified base. How do I do that?


Solution

  • The documentation there is out of date and misleading, and relative URIs are not supported (they have to resolve to an absolute URI, using the graph's BaseUri).

    Looking at the code, the InvalidOperationException is being raised in the ToString() method of BaseUriNode which is trying to get the AbosluteUri property of the underlying Uri instance. This has been the case in the code base since at least the 2.0 release.

    You could try changing the dotNetRDF code to avoid this - if you the implementation of BaseUriNode.ToString() in Libraries\dotNetRDF\Core\URINode.cs to something like:

    return _uri.IsAbsoluteUri ? _uri.AbsoluteUri : _uri.ToString();
    

    That would prevent the exception you see when creating relative URI Nodes. I'm a bit wary of doing this in main dotNetRDF project as it seems like it would have some much deeper implications across the rest of the code-base, but as a quick hack it could get you on the way to serializing the data you need to.