kasei / perlrdf

Deprecated in favor of the Attean package
26 stars 25 forks source link

preserve namespaces from Turtle? #130

Closed VladimirAlexiev closed 9 years ago

VladimirAlexiev commented 9 years ago

cc @nichtich

When I parse a Turtle into a model, I'd like the prefixes to be preserved in the model. (I know I can redefine a prefix in the same turtle but who does that? Take the last one in such case).

I'll be converting the turtle RDF to a diagram (PlantUML) and I want to print qnames not URLs (that's critical for a diagram).

RDF::Trine::Exporter::GraphViz uses RDF::NS i.e. the prefix.cc service. That's almost ok, but not all prefixes are or will ever be registered there: prefix.cc does not allow dash, underscore or capital letters, and that's by design. So eg aat: is registered but aat_term: can not be registered.

I'm new to Trine but I looked at RDF::Trine::Model and can't seem to find if it saves namespaces at all. There are a gazillion namespace modules on CPAN but none seem to do what I need.

Please give me a pointer here :-)

kasei commented 9 years ago

I'm not sure it's well documented, but you can do this with a NamespaceMap object passed to the parser:

my $map     = RDF::Trine::NamespaceMap->new();
my $parser  = RDF::Trine::Parser->new('turtle', namespaces => $map);
$parser->parse_file_into_model( $base, $test_file, $model, namespaces => $map );

foreach my $name ($map->list_prefixes) {
    my $ns  = $map->namespace_uri($name);
    print "$name\t$ns\n";
}

After parsing, the map object will contain all the namespaces used during parsing. Some serializers will also let you pass in the namespace map to allow round-trip parsing and serializing with the same namespaces.

VladimirAlexiev commented 9 years ago

Thanks!

I started writing a module RDF::Prefixes::Curie that aggressively prefixizes names (even starting with digits or including slash/dash). It feeds from a Turtle file, but the above is a better way.

Would be nice to also save the base. My module saves it in a key @base.

kasei commented 9 years ago

Good idea about supporting base uris. I've opened #131 to deal with that (and closing this issue).