How can I modify or remove properties values? - Jena API
I'm using Jena. I would like to know if there is a method that allows to modify or remov开发者_JAVA百科e properties values of an instance?
Thanks
Statements in Jena are, by design, immutable. To change the value of a property p
of some subject s
, you need to add a new statement with the same subject and predicate, and remove the old statement. This is always true in Jena, even if the API sometimes hides this from you. For example, OntResource
and its subclasses have a variety of setProperty
variants, but under the hood these are performing the same add-the-new-triple-and-delete-the-old process.
It depends which Jena API you are using. For instance, if you are using Jena 3.0 and the Model
API, you can use Model.remove(Statement)
to remove a property by choosing the appropriate subject/predicate/object for the Statement. Modification can be achieved by removing the old version of a Statement and adding the new version.
To only remove the statement itself, i.e. the relation between the instance and the property value, you can use: OntResource.removeProperty(Property, RDFNode)
If you want to remove the property value altogether, i.e. the value and all relations to it, you can use: OntResource.remove()
I had the similar task: I need to delete the property with the specified value. Hope the following code snippet will help someone.
public void removeLabel(String language, String value) {
NodeIterator nodeIterator = resource.getModel().listObjectsOfProperty(RDFS.label);
RDFNode foundToDelete = null;
while (nodeIterator.hasNext()) {
RDFNode next = nodeIterator.next();
boolean langsAreIdentical = next.asLiteral().getLanguage().equals(language);
boolean valuesAreIdentical = next.asLiteral().getLexicalForm().equals(value);
if (langsAreIdentical && valuesAreIdentical) {
foundToDelete = next;
break;
}
}
resource.getModel().remove(resource, RDFS.label, foundToDelete);
}
精彩评论