将前缀名称替换为SPARQL Query中没有前缀的URI

时间:2016-06-29 17:26:59

标签: java sparql jena

我从服务中获取SPARQL查询字符串,该字符串类似于以下查询:

SELECT * FROM { ?s owl:sameAs ?p } 

如果我尝试用QueryFactory类解析它,我会得到完全有意义的Unresolved Prefixed Name Exception

我有一个属性文件,用于映射predefined namespace prefixes

目前我有一个解决方法,如下所示:

Iterator<String> it = prefixConfig.getKeys();
String prefixes = "";
while(it.hasNext()) {
    String p = it.next();
    prefixes += "PREFIX " + p + ":<" + prefixConfig.getString(p) + "> ";
}

Query q = QueryFactory.create(prefixes + query);
it = prefixConfig.getKeys();
while(it.hasNext()) {
    String p = it.next();
    q.getPrefixMapping().removeNsPrefix(p);
}

query = q.toString();

这有效,但我对这个解决方案一点都不满意,所以我的问题是:

有没有一种方法可以替换SPARQL查询字符串中的前缀或只添加相关的前缀?

提前多多感谢!

1 个答案:

答案 0 :(得分:0)

public static String replacePrefixes(String query, PrefixMapping pmap){
    /* With Prologue and the parse method, 
     * the queryString gets parsed without an error
     */
    Prologue prog = new Prologue();
    prog.setPrefixMapping(pmap);
    Query q = QueryFactory.parse(new Query(prog), query, null, null);
    //Set Prefix Mapping
    q.setPrefixMapping(pmap);
    //remove PrefixMapping so the prefixes will get replaced by the full uris
    q.setPrefixMapping(null);       
    return q.serialize();
}

这对我有用:)