我正在使用Jena,我想创建一个模型,然后从包含RDF的String中读取其内容。例如:
String s= "<rdf:RDF
xmlns:res="http://www.w3.org/2005/sparql-results#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about="http://www.w3.org/2005/sparql-results#ResultSet">
<res:solution rdf:nodeID="r0"/>
<res:solution rdf:nodeID="r1"/>
<res:solution rdf:nodeID="r2"/>
</rdf:Description>
</rdf:RDF>";
目前,我使用这些说明:
Model rdf = ModelFactory.createDefaultModel();
InputStream in = FileManager.get().open(s);
if (in == null) {
throw new IllegalArgumentException("File: " + s+ " not found");
}
rdf.read(in, "");
这些仅在s
是文件名(例如s="./myFile.rdf"
)时才有效,而不是在我放置包含整个RDF的String时。
答案 0 :(得分:2)
Model.read(String,...)
方法使用字符串参数作为文件名。要从字符串中读取RDF内容,可以创建ByteArrayInputStream并使用Model.read(InputStream,...)
方法。例如,使用Model.read(InputStream in, String base)读取您的模型,然后将其写回Turtle:
import java.io.ByteArrayInputStream;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
public class ReadModelFromString {
public static void main(String[] args) {
final String modelText = "\n"
+ "<rdf:RDF \n"
+ " xmlns:res=\"http://www.w3.org/2005/sparql-results#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"> \n"
+ " <rdf:Description rdf:about=\"http://www.w3.org/2005/sparql-results#ResultSet\">\n"
+ " <res:solution rdf:nodeID=\"r0\"/>\n"
+ " <res:solution rdf:nodeID=\"r1\"/>\n"
+ " <res:solution rdf:nodeID=\"r2\"/>\n"
+ " </rdf:Description>\n" + "</rdf:RDF>";
final Model model = ModelFactory.createDefaultModel();
model.read(new ByteArrayInputStream(modelText.getBytes()), null);
model.write(System.out, "TTL");
}
}
产生
@prefix res: <http://www.w3.org/2005/sparql-results#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
res:ResultSet
res:solution
[] ;
res:solution
[] ;
res:solution
[] .