我已经尝试用raptor2C库解析一些RDF/XML文件一段时间了。此示例代码将读取NTriples文件并打印它,但不读取RDF/XML。
来自猛禽教程:
#include <stdio.h>
#include <raptor2.h>
/* rdfcat.c: parse any RDF syntax and serialize to RDF/XML-Abbrev */
static raptor_serializer* rdf_serializer;
static void
serialize_triple(void* user_data, raptor_statement* triple)
{
raptor_serializer_serialize_statement(rdf_serializer, triple);
}
static void
declare_namespace(void* user_data, raptor_namespace *nspace)
{
raptor_serializer_set_namespace_from_namespace(rdf_serializer, nspace);
}
int
main(int argc, char *argv[])
{
raptor_world *world = NULL;
raptor_parser* rdf_parser = NULL;
unsigned char *uri_string;
raptor_uri *uri, *base_uri;
world = raptor_new_world();
uri_string = raptor_uri_filename_to_uri_string(argv[1]);
uri = raptor_new_uri(world, uri_string);
base_uri = raptor_uri_copy(uri);
/* Ask raptor to work out which parser to use */
rdf_parser = raptor_new_parser(world, "guess");
raptor_parser_set_statement_handler(rdf_parser, NULL, serialize_triple);
raptor_parser_set_namespace_handler(rdf_parser, NULL, declare_namespace);
rdf_serializer = raptor_new_serializer(world, "rdfxml-abbrev");
raptor_serializer_start_to_file_handle(rdf_serializer, base_uri, stdout);
raptor_parser_parse_file(rdf_parser, uri, base_uri);
raptor_serializer_serialize_end(rdf_serializer);
raptor_free_serializer(rdf_serializer);
raptor_free_parser(rdf_parser);
raptor_free_uri(base_uri);
raptor_free_uri(uri);
raptor_free_memory(uri_string);
raptor_free_world(world);
return 0;
}
以下是维基百科中以两种格式编写的相同RDF的示例。第一个版本打印(有几个错误,但我认为这不重要),但第二个版本没有。
NTriples:
<http://www.w3.org/2001/sw/RDFCore/ntriples/> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://xmlns.com/foaf/0.1/Document> .
<http://www.w3.org/2001/sw/RDFCore/ntriples/> <http://purl.org/dc/terms/title> "N-Triples"@en-US .
<http://www.w3.org/2001/sw/RDFCore/ntriples/> <http://xmlns.com/foaf/0.1/maker> _:art .
<http://www.w3.org/2001/sw/RDFCore/ntriples/> <http://xmlns.com/foaf/0.1/maker> _:dave .
_:art <http://www.w3.org/1999/02/22-rdf-syntax-ns#> <http://xmlns.com/foaf/0.1/Person> .
_:art <http://xmlns.com/foaf/0.1/name> "Art Barstow".
_:dave <http://www.w3.org/1999/02/22-rdf-syntax-ns#> <http://xmlns.com/foaf/0.1/Person> .
_:dave <http://xmlns.com/foaf/0.1/name> "Dave Beckett".
RDFXML:
<rdf:RDF
xmlns="http://xmlns.com/foaf/0.1/"
xmlns:dc="http://purl.org/dc/terms/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<Document rdf:about="http://www.w3.org/2001/sw/RDFCore/ntriples/">
<dc:title xml:lang="en-US">N-Triples</dc:title>
<maker>
<Person rdf:nodeID="art">
<name>Art Barstow</name>
</Person>
</maker>
<maker>
<Person rdf:nodeID="dave">
<name>Dave Beckett</name>
</Person>
</maker>
</Document>
</rdf:RDF>
有什么想法吗?谢谢
编辑:RDFXML应该是有效的,因为它通过了W3C RDF验证器。
EDIT:明确地将解析器设置为"rdfxml"没有帮助。事实上,我刚刚从这个例子中发现了猜测选项,我很兴奋,因为之前我一直在手动检查扩展并用"ntriples"或"rdfxml"调用它。
它仍然只是猜测输入格式是什么-解析器是"猜测":
/* Ask raptor to work out which parser to use */
猜测可能是错误的。显式地将解析器设置为"ntriples"或"rdfxml",它不会猜测,它会准确地解析你给它的内容。