树像三胞胎的视图,并删除URI的

问题描述 投票:1回答:1

我在java中编写了一个代码,用于读取本体并打印三元组。代码工作正常。我想在输出中隐藏URI,并以树形层次结构形式打印输出。目前它给我输出线。知道我怎么能这样做。

Tree Form Like:

Thing
     Class
         SubClass
            Individual
              so on ...

这是ReadOntology类,我在servlet中使用这个类。

public class ReadOntology {

    public static OntModel model;

    public static void run(String ontologyInFile) {

        model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, null);
        InputStream ontologyIn = FileManager.get().open(ontologyInFile);

        loadModel(model, ontologyIn);
    }

    protected static void loadModel(OntModel m, InputStream ontologyIn) {
        try {
             m.read(ontologyIn, "RDF/XML");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

这是servlet

public class Ontology extends HttpServlet{

    OntClass ontClass = null;

    public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
    {

        PrintWriter out = res.getWriter();
        ServletContext context = this.getServletContext();
        String fullPath = context.getRealPath("/WEB-INF/Data/taxi.owl");
        ReadOntology.run(fullPath);

        SimpleSelector selector = new SimpleSelector(null, null, (RDFNode)null);

        StmtIterator iter = ReadOntology.model.listStatements(selector);
        while(iter.hasNext()) {
           Statement stmt = iter.nextStatement();
           out.print(stmt.getSubject().toString());
           out.print(stmt.getPredicate().toString());
           out.println(stmt.getObject().toString());
        }
    }
}
eclipse servlets jena ontology
1个回答
1
投票

作为实现目标的一步,它按主题对语句进行分组,并且谓词仅显示本地名称:

ResIterator resIt = ReadOntology.model.listSubjects()
while (resIt.hasNext()) {
    Resource r = resIt.nextResource();
    out.println(r);
    StmtIterator iter = r.listProperties();
    while (iter.hasNext()) {
        Statement stmt = iter.nextStatement();
        out.print("   ");
        out.print(stmt.getPredicate().getLocalName());
        out.println(stmt.getObject());
    }
}

ResourceModel的API中有很多有用的方法。

要渲染完整的类树,请使用OntModelOntClass上的方法。也许:

private void printClass(Writer out, OntClass clazz, int indentation) {
   String space = '    '.repeat(indentation);

   // print space + clazz.getLocalName()
   ...
   // iterate over clazz.listSubClasses(true)
   // and call printClass for each with indentation increased by 1
   ...
   // iterator over clazz.listInstances()
   // and print all their properties as in the
   // snippet above but with space added
}

然后在服务方法中,迭代OntModel的类,对于任何hasSuperClass()为false的地方,调用printClass(out, clazz, 0)

© www.soinside.com 2019 - 2024. All rights reserved.