如何把一个String类型的sparql语句,解析出一系列triple

我只在stack overflow上找到了一个不大好用的方案,仅供参考。
同道中人如果有会其他方法的欢迎交流啦~

public static ListIterator<TriplePath> triplePaths;
public static void parseSparql(String queryString){
        Query query = QueryFactory.create(queryString);

        ElementWalker.walk( query.getQueryPattern(), 
                new ElementVisitorBase() {
                    @Override
                    public void visit(ElementPathBlock el) {
                        ListIterator<TriplePath> it = el.getPattern().iterator();
                        //这个迭代器中装载的都是这个sparql语句的triplepath,可以调用asTriple语句获得triple
                        //这个it是局部变量,怎么把他取出来呢
                        triplePaths = it;
                    }
        });

triplePaths是类中的一个静态变量,我不知道如何把visit方法中的局部变量it取出来,所以用了这个不大聪明的方法,如果有另外的方法就更好啦。

这个方法用于ParseSparql类外访问解析结果

public static List<Triple> getTriplesInSparql(){
        List<Triple> triples = new ArrayList<Triple>();

        while(triplePaths.hasNext()){
            triples.add(triplePaths.next().asTriple());
        }
        return triples;
    }

Main方法中

String queryString = "PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT ?type WHERE {<http://cs.neu.edu.cn/rdf/schema/example#c2> rdf:type ?type. }";
        ParseSparql.parseSparql(queryString);
        List<Triple> triples = ParseSparql.getTriplesInSparql();
        for(Triple trp : triples){
            System.out.println(trp.toString());
        }

输出结果

http://cs.neu.edu.cn/rdf/schema/example#c2 @rdf:type ?type

猜你喜欢

转载自blog.csdn.net/Lqq77s/article/details/73808684
今日推荐