使用 Apache Jena 读取 RDF:foaf 文件

Read RDF:foaf file with Apache Jena

我在读取使用 foaf 标签的 RDF 文件时遇到问题。我想用 Apache Jena 阅读它。以下是 RDF 文件的片段。

<rdf:RDF xmlns="http://test.example.com/"     xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"     xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"     xmlns:foaf="http://xmlns.com/foaf/0.1/">
<foaf:Person rdf:about="http://test.example.com/MainPerson.rdf">
<foaf:firstName>John</foaf:firstName>
<foaf:lastName>Doe</foaf:lastName>
<foaf:nick>Doe</foaf:nick>
<foaf:gender>Male</foaf:gender>
<foaf:based_near>Honolulu</foaf:based_near>
<foaf:birthday>08-14-1990</foaf:birthday>
<foaf:mbox>john@example.com</foaf:mbox>
<foaf:homepage rdf:resource="http://www.example.com"/>
<foaf:img rdf:resource="http://weknowmemes.com/wp-content/uploads/2013/09/wat-meme.jpg"/>
<foaf:made>
Article: Developing applications in Java
</foaf:made>
<foaf:age>24</foaf:age>
<foaf:interest>
Java, Java EE (web tier), PrimeFaces, MySQL, PHP, OpenCart, Joomla,   Prestashop, CSS3, HTML5
</foaf:interest>
<foaf:pastProject rdf:resource="http://www.supercombe.si"/>
<foaf:status>Student</foaf:status>
<foaf:geekcode>M+, L++</foaf:geekcode>
<foaf:knows>
<foaf:Person>
<rdfs:seeAlso rdf:resource="http://test.example.com/Person.rdf"/>
</foaf:Person>
</foaf:knows>
<foaf:knows>
<foaf:Person>
<rdfs:seeAlso rdf:resource="http://test.example.com/Person2.rdf"/>
</foaf:Person>
</foaf:knows>
<foaf:knows>
<foaf:Person>
<rdfs:seeAlso rdf:resource="http://test.example.com/Person3.rdf"/>
</foaf:Person>
</foaf:knows>
</foaf:Person>
</rdf:RDF>

我只是不明白如何在常规 POJO 对象中使用 Apache Jena 读取这些数据。任何帮助将不胜感激(无法在网上找到此类解析的教程)。

不知道我是否理解你的问题。但是如果你需要将 RDF 文件读取到一个 POJO 对象,你有很多选择。例如,您可以使用 Jena 将 rdf 文件读取到模型中,然后使用框架建议的方法创建 POJO 对象以获取属性的值。 这是一个从文件

中提取foaf:firstName 的代码示例
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.util.FileManager;

public class Test {
    //First, create a Jena model and use FileManager to read the file
    public static Model model = ModelFactory.createDefaultModel();
    public static void main(String[] args) {
       //Use FileManager to read the file and add it to the Jena model
        FileManager.get().readModel(model, "test.rdf");
       //Apply methods like getResource, getProperty, listStatements,listLiteralStatements ...
       //to your model to extract the information you want
        Resource person = model.getResource("http://test.example.com/MainPerson.rdf");
        Property firstName = model.createProperty("http://xmlns.com/foaf/0.1/firstName");
        String firstNameValue = person.getProperty(firstName).getString();
        System.out.println(firstNameValue);

    }
}

您可以在 POJO class 的设置器中使用这些方法。可以找到很好的介绍here