在 Jena 模型中解析文件后,您可以使用以下内容进行迭代和过滤:
//Property to filter the model
Property geoProperty =
model. createProperty("http://www.w3.org/2003/01/geo/wgs84_pos#",
"geometry");
//Iterator based on a Simple selector
StmtIterator iter =
model.listStatements(new SimpleSelector(null, geoProperty, (RDFNode)null));
//Loop to traverse the statements that match the SimpleSelector
while (iter.hasNext()) {
Statement stmt = iter.nextStatement();
System.out.print(stmt.getSubject().toString());
System.out.print(stmt.getPredicate().toString());
System.out.println(stmt.getObject().toString());
}
SimpleSelector
允许您传递任何(主语、谓语、宾语)模式来匹配模型中的语句。在您的情况下,如果您只关心特定谓词,则构造函数的第一个和第三个参数为空。
允许过滤两个不同的属性
要允许更复杂的过滤,您可以在接口中实现该selects
方法,
如下所示:SimpleSelector
Property geoProperty = /* like before */;
Property countryLargestCityProperty =
model. createProperty("http://dbpedia.org/property/",
"countryLargestCity");
SimpleSelector selector = new SimpleSelector(null, null, (RDFNode)null) {
public boolean selects(Statement s)
{ return s.getPredicate().equals(geoProperty) ||
s.getPredicate().equals(countryLargestCityProperty) ;}
}
StmtIterator iter = model.listStatements(selector);
while(it.hasNext()) {
/* same as in the previous example */
}
编辑:包括一个完整的例子
此代码包含一个适用于我的完整示例。
import com.hp.hpl.jena.util.FileManager;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.SimpleSelector;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.rdf.model.Statement;
public class TestJena {
public static void main(String[] args) {
FileManager fManager = FileManager.get();
fManager.addLocatorURL();
Model model = fManager.loadModel("http://dbpedia.org/data/Ireland.rdf");
Property geoProperty =
model. createProperty("http://www.w3.org/2003/01/geo/wgs84_pos#",
"geometry");
StmtIterator iter =
model.listStatements(new SimpleSelector(null, geoProperty,(RDFNode) null));
//Loop to traverse the statements that match the SimpleSelector
while (iter.hasNext()) {
Statement stmt = iter.nextStatement();
if (stmt.getObject().isLiteral()) {
Literal obj = (Literal) stmt.getObject();
System.out.println("The geometry predicate value is " +
obj.getString());
}
}
}
}
这个完整的例子打印出来:
The geometry predicate value is POINT(-7 53)
关联数据注释
http://dbpedia.org/page/Ireland
是资源的 HTML 文档版本http://dbpedia.org/resource/Ireland
为了获得 RDF,您应该解决:
http://dbpedia.org/data/Ireland.rdf
或者
http://dbpedia.org/resource/Ireland
+ Accept: application/rdfxml
在 HTTP 标头中。有了curl
它会是这样的:
curl -L -H 'Accept: application/rdf+xml' http://dbpedia.org/resource/Ireland