SoulRayder SoulRayder -4 years ago 130
Java Question

How to write a SPARQL query for retrieving data from OWL file

I have generated an owl file using Protege. Now I wish to access all the stationCode property values of all instances of a class RailwayStation from it.

My OWL file contains the following format

<?xml version="1.0"?>
<owl:Ontology rdf:about="">
<owl:imports rdf:resource=""/>
<owl:imports rdf:resource=""/>
<rdfs:Class rdf:ID="BusStand"/>
<rdfs:Class rdf:ID="Eatery"/>
<rdfs:Class rdf:ID="Train"/>
<rdfs:Class rdf:ID="Hospital"/>
<rdfs:Class rdf:ID="City"/>
<rdfs:Class rdf:ID="RailwayStation"/>
<rdfs:Class rdf:ID="Airport"/>
<rdfs:Class rdf:ID="TouristSpot"/>
<rdfs:Class rdf:ID="Schedule"/>
<RailwayStation rdf:ID="RailwayStation_YPR">
<stationCode rdf:datatype="">


How do I write a SPARQL query for this purpose?

My current query is this :

String querystr = "PREFIX rdf:<>"+
"PREFIX owl:<>"+
"PREFIX rdfs:<>"+

"?RailwayStation stationCode ?x ."+

But it gives an exception like this:

Exception in thread "main" com.hp.hpl.jena.query.QueryParseException: Lexical error at line 1, column 194. Encountered: " " (32), after : "stationCode"
at com.hp.hpl.jena.sparql.lang.ParserSPARQL11.perform(
at com.hp.hpl.jena.sparql.lang.ParserSPARQL11.parse$(
at com.hp.hpl.jena.sparql.lang.SPARQLParser.parse(
at com.hp.hpl.jena.query.QueryFactory.parse(
at com.hp.hpl.jena.query.QueryFactory.create(
at com.hp.hpl.jena.query.QueryFactory.create(
at com.hp.hpl.jena.query.QueryFactory.create(
at org.iiitb.jena.Main.sprqltest(
at org.iiitb.jena.Main.main(

Answer Source

There is some problems with your file and your query. First, you have to know that when you declare a base namespace in your xml/rdf file, all the tags used without a specific namespace will be added to your base namespace But in your case I think that Protege genereted this namespace for you. Concerning your file, add # or / to the end of your base namespace.

Finally, for your query : Add the prefix PREFIX base: <> just as you did for rdf and rdfs...

After this, you wish to access all the stationCode property values of all instances of a class RailwayStation, the sparql query answering this is :

PREFIX rdf: <>
PREFIX base: <>
select * 
where { ?s a <> .
        ?s <> ?o}

I tested it in your file and it returns the good result. I deliberately didn't use the namespace in my query so you can immediately test it in your data without changing the namespaces ;) Good luck

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download