我正在编写一个应用程序,用户可以在其中上传 .rdf 文件,然后在其上执行 SPARQL 查询。现在我被困在如何格式化查询结果的问题上。例如:ASK
-Query 输出布尔值,SELECT
-Query 返回 ResultSet。CONSTRUCT
并DESCRIBE
返回一个新的 RDF-Graph。
如何以表单形式获取给定查询的结果以将其传递给我的视图?我希望在那里打印出一个 HTML 表格。
为了更好地理解我的问题,我创建了这个简约的代码示例:
import java.io.InputStream;
import com.hp.hpl.jena.*;
public class playground {
public static void main(String[] args) {
InputStream in = FileManager.get().open("vc-db-1.rdf");
Model model = ModelFactory.createDefaultModel();
model.read(in, null);
String queryStringSelect = "SELECT ?subject ?predicate ?object WHERE { ?subject ?predicate ?object }";
String queryStringAsk = "ASK WHERE { ?subject ?predicate ?object }";
String queryStringDescribe = "DESCRIBE * WHERE { ?subject ?predicate ?object }";
String queryStringConstruct = "CONSTRUCT { ?subject ?predicate ?object } WHERE { ?subject ?predicate ?object }";
QueryExecution qe = QueryExecutionFactory.create(queryStringDescribe,
model);
Query q = QueryFactory.create(queryStringDescribe);
int queryType = q.getQueryType();
switch (queryType) {
case Query.QueryTypeAsk:
boolean b = qe.execAsk(); // Result that has to be formatted
ResultSetFormatter.outputAsTSV(System.out, b);
break;
case Query.QueryTypeConstruct:
model = qe.execConstruct(); // Result that has to be formatted
model.write(System.out);
break;
case Query.QueryTypeDescribe:
model = qe.execDescribe(); // Result that has to be formatted
model.write(System.out);
break;
case Query.QueryTypeSelect:
ResultSet results = qe.execSelect(); // Result that has to be
// formatted
ResultSetFormatter.outputAsTSV(System.out, results);
break;
}
model.close();
qe.close();
}
}
可以在此处下载提及的 .rdf 文件:http: //jena.apache.org/tutorials/sparql_data/vc-db-1.rdf