当我们面前没有整个问题(我们没有数据)时,很难确切知道问题出在哪里,但这里有一个包含两个类的小本体,每个类都有一个标签:
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:owl="http://www.w3.org/2002/07/owl#"
xmlns="http://example.org/labelled-classes#"
xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#">
<owl:Ontology rdf:about="http://example.org/labelled-classes"/>
<owl:Class rdf:about="http://example.org/labelled-classes#B">
<rdfs:label>Class B</rdfs:label>
</owl:Class>
<owl:Class rdf:about="http://example.org/labelled-classes#A">
<rdfs:label>Class A</rdfs:label>
</owl:Class>
</rdf:RDF>
当我运行这个查询
prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>
select ?class where {
?class rdfs:label "Class A"
}
使用 Jena 的命令行 ARQ 对数据进行对比,我得到以下结果:
$ arq --data labelled-classes.owl --query classByLabel.sparql
-------------------------------------------
| class |
===========================================
| <http://example.org/labelled-classes#A> |
-------------------------------------------
所以查询看起来没问题。现在的问题是我们在耶拿做什么?下面是一些对相同数据执行相同查询的 Java 代码:
import java.io.ByteArrayInputStream;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
public class ClassByLabel {
public static void main(String[] args) {
final String rdfxmlContent = ""+
"<rdf:RDF\n" +
" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" +
" xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n" +
" xmlns=\"http://example.org/labelled-classes#\"\n" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n" +
" xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\">\n" +
" <owl:Ontology rdf:about=\"http://example.org/labelled-classes\"/>\n" +
"<owl:Class rdf:about=\"http://example.org/labelled-classes#B\">\n" +
" <rdfs:label>Class B</rdfs:label>\n" +
" </owl:Class>\n" +
" <owl:Class rdf:about=\"http://example.org/labelled-classes#A\">\n" +
" <rdfs:label>Class A</rdfs:label>\n" +
" </owl:Class>\n" +
"</rdf:RDF>\n" +
"";
final String queryString = "" +
"prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n" +
"\n" +
"select ?class where {\n" +
" ?class rdfs:label \"Class A\"\n" +
"}\n" +
"";
final Model model = ModelFactory.createDefaultModel();
model.read( new ByteArrayInputStream( rdfxmlContent.getBytes()), null, "RDF/XML" );
final ResultSet results = QueryExecutionFactory.create( queryString, model ).execSelect();
while ( results.hasNext() ) {
final QuerySolution solution = results.nextSolution();
System.out.println( "?class:\t"+solution.get( "class" ));
System.out.println( "?o1:\t"+solution.get( "o1" ));
}
}
}
输出是:
?class: http://example.org/labelled-classes#A
?o1: null
您的数据可能有些奇怪,但我希望您正在检索o1
而不是c
. 请注意,检索未绑定的变量不会产生错误,而只会返回null
.