如何获取链接到Jena资源的资源列表?

时间:2013-03-21 20:48:41

标签: rdf jena

我使用Jena API创建了一个模型:

public static void main(String[] args) {
    Model model = ModelFactory.createDefaultModel();

    Resource alice = ResourceFactory.createResource("http://example.org/alice");

    Resource bob = ResourceFactory.createResource("http://example.org/bob");

    Resource charlie = ResourceFactory.createResource("http://example.org/charlie");

    model.add (alice, RDF.type, FOAF.Person);
    model.add (alice, FOAF.name, "Alice");
    model.add (alice, FOAF.mbox, ResourceFactory.createResource("mailto:alice@example.org"));
    model.add (alice, FOAF.knows, bob);
    model.add (alice, FOAF.knows, charlie);

    model.write(System.out, "RDF/XML-ABBREV");
}

该程序的输出是:

<rdf:RDF xmlns:rdf="w3.org/1999/02/22-rdf-syntax-ns#"
         xmlns:j.0="xmlns.com/foaf/0.1/">
    <j.0:Person rdf:about="example.org/alice">
        <j.0:knows rdf:resource="example.org/charlie"/>
        <j.0:knows rdf:resource="example.org/bob"/>
        <j.0:mbox rdf:resource="mailto:alice@example.org"/>
        <j.0:name>Alice</j.0:name>
    </j.0:Person>
</rdf:RDF>

现在如何获取链接到某个资源的资源列表?

例如:爱丽丝知道鲍勃和查理。 Alice,Bob和Charlie是资源,资源Alice知道另外两个资源。现在如何得到名字[鲍勃,查理]?

1 个答案:

答案 0 :(得分:3)

Jena的Java API文档仅显示there is a method

NodeIterator listObjectsOfProperty(Resource s, Property p)

这应该适用于您的示例:

NodeIterator friends = model.listObjectsOfProperty(alice, FOAF.knows);

然后你可以迭代friends与每个朋友(或熟人)做点什么。