gpt4 book ai didi

java - 使用 Jena Library 从 Java 中的 RDF 网页中提取 URI

转载 作者:行者123 更新时间:2023-12-02 00:12:14 25 4
gpt4 key购买 nike

我编写了以下代码,用于从链接数据应用程序的内容类型为 application/rdf-xml 的网页中提取 URI。

public static void test(String url) {
try {
Model read = ModelFactory.createDefaultModel().read(url);
System.out.println("to go");
StmtIterator si;
si = read.listStatements();
System.out.println("to go");
while(si.hasNext()) {
Statement s=si.nextStatement();
Resource r=s.getSubject();
Property p=s.getPredicate();
RDFNode o=s.getObject();
System.out.println(r.getURI());
System.out.println(p.getURI());
System.out.println(o.asResource().getURI());
}
}
catch(JenaException | NoSuchElementException c) {}
}

但是对于输入

<?xml version="1.0"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:ex="http://example.org/stuff/1.0/">
<rdf:Description rdf:about="http://www.w3.org/TR/rdf-syntax-grammar"
dc:title="RDF/XML Syntax Specification (Revised)">
<ex:editor>
<rdf:Description ex:fullName="Dave Beckett">
<ex:homePage rdf:resource="http://purl.org/net/dajobe/" />
</rdf:Description>
</ex:editor>
</rdf:Description>
</rdf:RDF>

输出是:

Subject URI is http://www.w3.org/TR/rdf-syntax-grammar
Predicate URI is http://example.org/stuff/1.0/editor
Object URI is null
Subject URI is http://www.w3.org/TR/rdf-syntax-grammar
Predicate URI is http://purl.org/dc/elements/1.1/title
Website is read

我需要输出中存在该页面上的所有 URI,以便为 RDF 页面构建网络爬虫。我需要输出中的所有以下链接:

       http://www.w3.org/TR/rdf-syntax-grammar
http://example.org/stuff/1.0/editor
http://purl.org/net/dajobe
http://example.org/stuff/1.0/fullName
http://www.w3.org/TR/rdf-syntax-grammar
http://purl.org/dc/elements/1.1/title

最佳答案

小错误:你的意思是application/rdf+xml(注意加号)。

无论如何,你的问题很简单:

catch(JenaException | NoSuchElementException c) {}

糟糕!您错过了此处抛出的错误,并且输出被截断:

System.out.println(o.asResource().getURI());

o 并不始终是资源,这会在三元组上中断

<http://www.w3.org/TR/rdf-syntax-grammar> dc:title "RDF/XML Syntax ..."

所以你需要警惕:

if (o.isResource()) System.out.println(o.asResource().getURI());

或者更具体:

if (o.isURIResource()) System.out.println(o.asResource().getURI());

这将跳过您在 ex:editor 中看到的 null 输出。

现在写一千遍我不会吞下异常:-)

关于java - 使用 Jena Library 从 Java 中的 RDF 网页中提取 URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12544134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com