How to get a list of resources linked to a resource in Jena?

半世苍凉 提交于 2019-12-02 12:40:08

问题


I created a Model using the Jena APIs:

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

The output from this program is:

<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>

Now how to get a list of resources linked to a certain resource?

For example: Alice knows Bob and Charlie. Alice, Bob and Charlie are resources, Resource Alice knows the other two resources. Now how to get the names [Bob, Charlie]?


回答1:


Jena's Java API documentation shows there is a method just for that:

NodeIterator listObjectsOfProperty(Resource s, Property p)

This should work in your example:

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

You can then iterate over friends to do something with each friend (or acquaintance).



来源:https://stackoverflow.com/questions/15557778/how-to-get-a-list-of-resources-linked-to-a-resource-in-jena

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!