Skip to content

Instantly share code, notes, and snippets.

@tpluscode
Created November 11, 2017 11:46
Show Gist options
  • Save tpluscode/f8d6975a6c8e6ab33cba7bced778ba99 to your computer and use it in GitHub Desktop.
Save tpluscode/f8d6975a6c8e6ab33cba7bced778ba99 to your computer and use it in GitHub Desktop.
Prepending a comment before serialized RDF

CommentHeaderWriter

Simple decorator of IRdfWriter which prepends the output with a comment string.

Note that it is up to the caller to provide a string which will be a valid comment according to the syntax of chose RDF serialization.

public class CommentHeaderWriter : BaseRdfWriter
{
private readonly IRdfWriter inner;
private readonly string header;
public CommentHeaderWriter(IRdfWriter writer, string header)
{
this.inner = writer;
this.header = header;
}
public override void Save(IGraph g, string filename)
{
using (var stream = File.Open(filename, FileMode.Create))
{
this.Save(g, new StreamWriter(stream, new UTF8Encoding(Options.UseBomForUtf8)));
}
}
protected override void SaveInternal(IGraph graph, TextWriter output)
{
output.WriteLine(_header);
output.WriteLine();
this.inner.Save(graph, output);
}
public override event RdfWriterWarning Warning
{
add
{
this.inner.Warning += value;
}
remove
{
this.inner.Warning -= value;
}
}
}
class Program
{
public static void Main()
{
Graph graph = new Graph();
graph.Assert(
new VDS.RDF.Triple(
graph.CreateBlankNode(),
graph.CreateUriNode(new Uri("http://schema.org/name")),
graph.CreateLiteralNode("Tomasz")));
var comment = "# Created with dotNetRDF";
var output = new System.IO.StringWriter();
var actualWriter = new CompressingTurtleWriter();
var writer = new CommentHeaderWriter(actualWriter, comment);
writer.Save(graph, output);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment