在没有 sparql 的情况下检索主题的对象和谓词

Retrieving object and predicate for a subject without sparql

我使用 getSubject() 通过模型检索了主题,对于这个主题,我想为它们各自的对象和谓词创建一个关系。如何在不使用 sparql 的情况下通过 jena 检索特定主题的对象和谓词?

获取给定模型m的特定主题的所有谓词和宾语:

// The resource you already had:
Resource subject; // = m.getResource(NAMESPACE + "subject");

// This creates a 'list' (iterator) over all the satements containing your subject
StmtIterator stmtIterator = m.listStatements(subject, null, (RDFNode) null);

// While you have not processed all these statements:
while (stmtIterator.hasNext()){

     // Grab the next statement
     Statement s = stmtIterator.next();

     // Retrieve the predicate(property) and the object from the statement
     Property predicate = s.getPredicate();
     Resource object = s.getObject();

     // Do something with your predicate
     // Do something with your object
}

然而,如果你的意思是你想从模型中获取一个谓词和一个主题,将其添加到你检索到的主题中:

Property property = m.getProperty(NAMESPACE + "propertyName");
Resource object = m.getResource(NAMESPACE + "objectName");
subject.addProperty(property, object);