我使用JENA库创建了一些RDF文件:Model model = ModelFactory.createDefaultModel();
...
现在我怎么能把它转换成字符串?
THX
答案 0 :(得分:13)
尝试这样的事情:
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");
答案 1 :(得分:0)
RDF模型是一组语句。每次向模型添加属性时,都会创建一个Statement ...并且RDF模型中的Statement也称为“ Triple ”,因为它有3个部分:Subject(Resource),谓词(属性)和对象(RDFNode - 可以是资源)。您可以在这些对象上调用toString方法,如下面的代码所示:
// 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(" .");
}
请注意上面代码中的'toString'方法。
来源/参考:Jena - RDF(查看“声明”部分)。