一、RDF的表示方法

RDF是一张图。它的表示方法由节点、箭头组成。节点是Resource或者Property(Literal),在Jena里面,一张图就是一个Model,Model也可以合并操作等。

  • Resource: 可以是一个人,他有一些属性,resource需要URI(唯一标识符来表示)
  • Property: 属性,属性的值也可以是Resource,可以用于连接Resource之间的关系。
  • Literal: 字符串属性

二、创建一个Model、Resource、添加属性

1
2
3
4
5
6
7
8
9
10
11
12
// some definitions
static String personURI = "http://somewhere/JohnSmith";
static String fullName = "John Smith";
// create an empty Model
Model model = ModelFactory.createDefaultModel();
// create the resource
Resource johnSmith = model.createResource(personURI);
// add the property
johnSmith.addProperty(VCARD.FN, fullName);

也可以写成下面简单的方式:

1
2
Resource johnSmith = model.createResource(personURI)
.addProperty(VCARD.FN, fullName);

属性的值也可以是一个空的resource,再给他一些属性值。

1
2
3
4
5
6
7
Resource johnSmith
= model.createResource(personURI)
.addProperty(VCARD.FN, fullName)
.addProperty(VCARD.N,
model.createResource() // 空的resource
.addProperty(VCARD.Given, givenName)
.addProperty(VCARD.Family, familyName));

三、Statements

Statements就是一个三元组。

  1. Subject: 箭头的起点(resource)
  2. Predicate: 谓语(property的描述)
  3. Object: 箭头的终点(resource或者literal)

Jena可以用listStatements()方法来返回一个迭代器,来遍历三元组。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// list the statements in the Model
StmtIterator iter = model.listStatements();
// print out the predicate, subject and object of each statement
while (iter.hasNext()) {
Statement stmt = iter.nextStatement(); // get next statement
Resource subject = stmt.getSubject(); // get the subject
Property predicate = stmt.getPredicate(); // get the predicate
RDFNode object = stmt.getObject(); // get the object
System.out.print(subject.toString());
System.out.print(" " + predicate.toString() + " ");
if (object instanceof Resource) {
System.out.print(object.toString());
} else {
// object is a literal
System.out.print(" \"" + object.toString() + "\"");
}
System.out.println(" .");
}

四、读写RDF

Jena可以把RDF写入到XML和写出XML文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// create an empty model
Model model = ModelFactory.createDefaultModel();
// use the FileManager to find the input file
InputStream in = FileManager.get().open( inputFileName );
if (in == null) {
throw new IllegalArgumentException(
"File: " + inputFileName + " not found");
}
// read the RDF/XML file
model.read(in, null);
// write it to standard out
model.write(System.out);