Search code examples
rdfjena

How can I get the used prefix from a Jena Resource?


Given a Jena Resource object (org.apache.jena.rdf.model.Resource), how can I get the prefix of the Resource?


Solution

  • resource and prefix are unrelated things. To work with prefixes there is a org.apache.jena.shared.PrefixMapping interface. Any model (org.apache.jena.rdf.model.Model) extends PrefixMapping. Also a graph (org.apache.jena.graph.Graph) provides access to the PrefixMapping.

    To get prefix from uri the method PrefixMapping#getNsURIPrefix(String) can be used. To get an URI from resource there is a #getURI method, which will return null in case it is anonymous resource.

    The PrefixMapping#getNsURIPrefix(String) will return the most recently added prefix, which does not guarantee it was the associated with the Resource. enter image description here

    src:https://jena.apache.org/documentation/javadoc/jena/org/apache/jena/shared/PrefixMapping.html#getNsURIPrefix-java.lang.String-