2

Can RDFlib take in lines of xml code to be put into a graph in python? I Know triples are generally what is used with RDFlib, but if I didn't have to convert them from XML to Turtle it would save a lot of work.

Johnnerz
  • 1,365
  • 4
  • 17
  • 29

1 Answers1

5

Assuming that when you say “xml code” you actually mean RDF/XML, and that you have the entire RDF/XML document, not just a snippet of it, then yes, RDFlib accepts it. The documentation page Loading and saving RDF starts with an example in N-Triples, but mentions how other formats are specified:

Reading an NT file

RDF data has various syntaxes (xml, n3, ntriples, trix, etc) that you might want to read. The simplest format is ntriples, a line-based format. Create the file demo.nt in the current directory with these two lines:

<http://bigasterisk.com/foaf.rdf#drewp> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://xmlns.com/foaf/0.1/Person> .
<http://bigasterisk.com/foaf.rdf#drewp> <http://example.com/says> "Hello world" .

You need to tell RDFLib what format to parse, use the format keyword-parameter to parse(), you can pass either a mime-type or the name (a list of available parsers is available). If you are not sure what format your file will be, you can use rdflib.util.guess_format() which will guess based on the file extension.

In your case, you just need to use the xml (which actually means RDF/XML) format:

>>> g.parse("demo.rdf", format="xml")
Community
  • 1
  • 1
Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353