How to get a list of resources linked to a resourc

2019-02-28 23:43发布

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

标签: rdf jena
1条回答
Emotional °昔
2楼-- · 2019-03-01 00:38

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

查看更多
登录 后发表回答