如何在 Jena 中动态地将项目添加到 rdflist/rdfcollection

How to add items to rdflist /rdfcollection dynamically in Jena

是否可以将项目动态添加到耶拿的 RDFList 中? 类似于:

RDFList list = model.createList(new RDFNode[] {});
//string with names of rdf classes
String[] parts = list.split("-");

for(int i = 0; i<parts.length; i++){
    OntClass oclass = model.getOntClass("http://example.org/"+parts[i]);  
    list.add(oclass);
}

我正在
com.hp.hpl.jena.rdf.model.EmptyListUpdateException: Attempt to add() to the empty list (rdf:nil)
提前致谢

在没有看到您的所有代码和某些值的情况下,我们无法确定发生了什么,但我认为这里的问题是您不能将 RDFList#add 与 empty 列表,我认为这就是您在开始时创建的内容。由于您正在创建一个没有元素的列表,因此您应该返回 rdf:nil,这是一个空列表。请注意 RDFList#add 的文档说:

If this list is the empty (nil) list, we cannot perform a side-effecting update without changing the URI of this node (from rdf:nil) to a blank-node for the new list cell) without violating a Jena invariant. Therefore, this update operation will throw an exception if an attempt is made to add to the nil list. Safe ways to add to an empty list include with(RDFNode) and cons(RDFNode).

你没有提到你是否得到了那个异常。

对于您的情况,我认为最简单的做法是创建 OntClasses 的数组,然后根据它们创建列表。也就是说,你可以做类似(未测试)的事情:

String[] parts = list.split("-");
RDFNode[] elements = new RDFNode[parts.length];

for(int i = 0; i<parts.length; i++){
    elements[i] = model.getOntClass("http://example.org/"+parts[i]);  
}

RDFList list = model.createList(elements);

或者,如果您想将 一起使用,如文档中所述,您可以执行以下操作(同样,未经测试):

RDFList list = model.createList(new RDFNode[] {});
//string with names of rdf classes
String[] parts = list.split("-");

for(int i = 0; i<parts.length; i++){
    OntClass oclass = model.getOntClass("http://example.org/"+parts[i]);  
    list = list.with(oclass);
}

有关此内容的更多信息,您可能会发现我的 this answer 以及相关的评论。您不是第一个遇到 RDFList 问题的人。