在java中使用jena API显示RDF

时间:2013-03-15 04:02:56

标签: rdf jena

我在StoryModel中创建了一些方法。如果代码中有任何错误,我真的很感激修正。

public class StoryModel {

    String dbName = "DB3";
    String sns =  "http://somebook/SemBook#";
    String ns;
    Dataset ds;
    OntModel om;

    // create model and connect to database
    public StoryModel(String storyName){

        ns = sns + storyName;
        ds = TDBFactory.createDataset(dbName);
        om = ModelFactory.createOntologyModel();

    }

    // create classes in model
    public void initModel() {

        om.createClass(ns + "Person");
        om.createClass(ns + "Event");
        om.createClass(ns + "Place");
        om.createClass(ns + "Time");
        om.createClass(ns + "Object");
        saveModel();
    }   

    //Read & write in database
    //Display it
    public void saveModel() {

        ds.begin(ReadWrite.WRITE);
        om.write(System.out, "RDF/XML-ABBREV");

    }

    // Create resource to class in model
    public Resource createResource(String resourceName, String clsName) {

        OntResource resource = om.createOntResource(ns + resourceName);
        String ruri = ns + resource;
        OntClass clsuri = om.getOntClass(ns + clsName);

        Individual i = om.createIndividual(ruri, clsuri);

        return i;

    }

    /*
     * Return an RDF resource object given the URI of the resource as a string. The
     * URI can be represented in full, or as a "prefix:localName".
     * @param resourceName The full URI of the resource
     * @return An RDF resource object
     */

    public Resource stringToResource( String resourceName ) {

        String resourceURI = om.expandPrefix( resourceName );

        return om.getResource( resourceURI );

    }

    // Delete the resource
    public void deleteResource(String resourceName) {

        try {
            OntResource resource = om.getOntResource(ns + resourceName);

            if (resource != null) 
            {
               resource.remove();
            }
            else {
                System.out.println("Resource not present");
            }   
        }
        catch (Exception e) { }         
    }
}

在SemBookMain中,我创建了一个模型,并使用在StoryModel中创建的方法将类初始化为资源并显示它

public class SemBookMain {

    public static void main(String[] args) {

        // create and initialize a model
        StoryModel sm = new StoryModel("alice");
        //sm.saveModel();
        sm.initModel();

        // add resources
        String clsName = "Person";
        String[] ar = {"Alice", "Peter", "Ben", "Robin"};

        for (String r : ar) {

            Resource res = sm.createResource(r, clsName);

        }
        sm.saveModel();

    }

}

我很抱歉,我在下面添加了输出作为评论,所以请查看我的评论。

我不了解ERROR 1& 2以及为什么不显示资源。有些东西我想念但是无法理解。

1 个答案:

答案 0 :(得分:2)

ds.begin(ReadWrite.WRITE);但没有ds.commit

initModel拨打saveModel,然后再次致电saveModel

遵循以下代码模式:

http://jena.apache.org/documentation/tdb/tdb_transactions.html#write-transactions