三胞胎的树状视图并删除 URI

Tree like view of Triplets and remove URI's

我在 java 中编写了一个代码,它读取 ontology 并打印三胞胎。代码工作正常。我想在输出中隐藏 URI,并以树层次结构形式打印输出。目前它给我输出行。知道我该怎么做吗。

Tree Form Like:

Thing
     Class
         SubClass
            Individual
              so on ...

这是 ReadOntology class,这是我在 servlet 中使用的 class。

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());
        }
    }
}

作为朝着您的目标迈出的一步,这将按主题对语句进行分组,并且对于谓词仅显示本地名称:

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());
    }
}

API 中有很多有用的方法 Resource and Model

要渲染完整的 class 树,请使用 OntModel and OntClass 上的方法。也许:

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 的 classes,对于任何 hasSuperClass() 为假的地方,调用 printClass(out, clazz, 0).