我使用JENA库创建了一些RDF文件:
Model model = ModelFactory.createDefaultModel();
...
现在,我该如何将它转换为字符串?
谢谢。试试这样:
String syntax = "RDF/XML-ABBREV"; // also try "N-TRIPLE" and "TURTLE"
StringWriter out = new StringWriter();
model.write(out, syntax);
String result = out.toString();
这里使用了Jena内置的写入器,它们可以将RDF图以各种支持的RDF语法输出,例如RDF/XML、Turtle和N-Triples。如果你只想将其转储到System.out
中,则更加简单:
model.write(System.out, "RDF/XML-ABBREV");
// 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(" .");
}
model.write()
一行代码实现同样的功能。 - cygri