public void ParsingRdfXmlAmpersands() { List<IRdfWriter> writers = new List<IRdfWriter>() { new RdfXmlWriter(), new FastRdfXmlWriter() }; IRdfReader parser = new RdfXmlParser(); Graph g = new Graph(); g.BaseUri = new Uri("http://example.org/ampersandsInRdfXml"); g.Assert(new Triple(g.CreateUriNode(), g.CreateUriNode(new Uri("http://example.org/property")), g.CreateUriNode(new Uri("http://example.org/a&b")))); g.Assert(new Triple(g.CreateUriNode(), g.CreateUriNode(new Uri("http://example.org/property")), g.CreateLiteralNode("A & B"))); foreach (IRdfWriter writer in writers) { try { Console.WriteLine(writer.GetType().ToString()); String temp = StringWriter.Write(g, writer); Console.WriteLine(temp); Graph h = new Graph(); StringParser.Parse(h, temp); Assert.AreEqual(g, h, "Graphs should be equal"); Console.WriteLine(); } catch (Exception ex) { TestTools.ReportError("Error", ex, true); } } }
public void ParsingRdfXmlEmptyStrings() { NTriplesFormatter formatter = new NTriplesFormatter(); RdfXmlParser domParser = new RdfXmlParser(RdfXmlParserMode.DOM); Graph g = new Graph(); domParser.Load(g, "empty-string-rdfxml.rdf"); Console.WriteLine("DOM Parser parsed OK"); foreach (Triple t in g.Triples) { Console.WriteLine(t.ToString(formatter)); } Console.WriteLine(); RdfXmlParser streamingParser = new RdfXmlParser(RdfXmlParserMode.Streaming); Graph h = new Graph(); streamingParser.Load(h, "empty-string-rdfxml.rdf"); Console.WriteLine("Streaming Parser parsed OK"); foreach (Triple t in h.Triples) { Console.WriteLine(t.ToString(formatter)); } Assert.AreEqual(g, h, "Graphs should be equal"); }
public IEnumerable<IDataObject> BindRdfDataObjects(XDocument rdfXmlDocument, IList<OrderingDirection> orderingDirections) { var g = new Graph(); #if PORTABLE || WINDOWS_PHONE var parser = new RdfXmlParser(RdfXmlParserMode.Streaming); // This is pretty nasty, having to deserialize only to go through parsing again parser.Load(g, new System.IO.StringReader(rdfXmlDocument.ToString())); #else var parser = new RdfXmlParser(RdfXmlParserMode.DOM); parser.Load(g, rdfXmlDocument.AsXmlDocument()); #endif var p = new VDS.RDF.Query.LeviathanQueryProcessor(new InMemoryDataset(g)); var queryString = MakeOrderedResourceQuery(orderingDirections); var sparqlParser = new SparqlQueryParser(); var query = sparqlParser.ParseFromString(queryString); var queryResultSet = p.ProcessQuery(query) as VDS.RDF.Query.SparqlResultSet; foreach (var row in queryResultSet.Results) { INode uriNode; if (row.TryGetBoundValue("x", out uriNode) && uriNode is IUriNode) { yield return BindRdfDataObject(uriNode as IUriNode, g); } } }
public static IGraph CreateNuspecGraph(XDocument nuspec, string baseAddress) { nuspec = NormalizeNuspecNamespace(nuspec); XslCompiledTransform transform = CreateTransform("xslt.nuspec.xslt"); XsltArgumentList arguments = new XsltArgumentList(); arguments.AddParam("base", "", baseAddress + "packages/"); arguments.AddParam("extension", "", ".json"); arguments.AddExtensionObject("urn:helper", new XsltHelper()); XDocument rdfxml = new XDocument(); using (XmlWriter writer = rdfxml.CreateWriter()) { transform.Transform(nuspec.CreateReader(), arguments, writer); } RdfXmlParser rdfXmlParser = new RdfXmlParser(); XmlDocument doc = new XmlDocument(); doc.Load(rdfxml.CreateReader()); IGraph graph = new Graph(); rdfXmlParser.Load(graph, doc); return graph; }
protected override void LoadGraph() { CreateGraph(); using (Stream stream = InnerObject.GetStream()) using (StreamReader reader = new StreamReader(stream, true)) { RdfXmlParser rdfXmlParser = new RdfXmlParser(); rdfXmlParser.Load(_graph, reader); } }
public static void Main(String[] args) { try { Console.WriteLine("Reading a RDF/XML format Test Graph"); RdfXmlParser parser = new RdfXmlParser(); Graph g = new Graph(); parser.Load(g, "JSONTest.rdf"); Console.WriteLine("Serializing back to RDF/JSON"); RdfJsonWriter writer = new RdfJsonWriter(); writer.Save(g, "JSONTest.rdf.json"); Console.WriteLine("Reading back from the RDF/JSON"); RdfJsonParser jsonparser = new RdfJsonParser(); Graph h = new Graph(); jsonparser.Load(h, "JSONTest.rdf.json"); Console.WriteLine("Outputting to NTriples"); NTriplesWriter ntwriter = new NTriplesWriter(); ntwriter.Save(h, "JSONTest.rdf.json.out"); Console.WriteLine("Reading a RDF/JSON format Test Graph with tons of Comments in it"); Graph i = new Graph(); jsonparser.Load(i, "JSONTest.json"); Console.WriteLine("Outputting to NTriples"); ntwriter.Save(i, "JSONTest.json.out"); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); if (ex.InnerException != null) { Console.WriteLine(ex.InnerException.Message); Console.WriteLine(ex.InnerException.StackTrace); } } }
/// <summary> /// Updates the underlying store with this as the new representation of the identified resource /// </summary> /// <param name="resourceUri">The resource for whom this is the representation</param> /// <param name="resourceDescription">The rdf xml document that describes the resource</param> public override void ApplyFragment(string resourceUri, XDocument resourceDescription) { try { var g = new Graph(); var rdfXmlParser = new RdfXmlParser(); rdfXmlParser.Load(g, new StringReader(resourceDescription.ToString())); var ntWriter = new NTriplesWriter(); var data = StringWriter.Write(g, ntWriter); var sparqlUpdate = ""; sparqlUpdate += "DELETE { GRAPH <" + GraphUri + "> { <" + resourceUri + "> ?x ?y }}"; sparqlUpdate += "USING <" + GraphUri + "> WHERE {<" + resourceUri + "> ?x ?y } ;"; sparqlUpdate += "INSERT DATA { GRAPH <" + GraphUri + "> { "; sparqlUpdate += data; sparqlUpdate += " }};"; // execute update var wr = WebRequest.Create(SparqlEndpoint) as HttpWebRequest; wr.ContentType = "application/sparql-update"; wr.Method = "POST"; var ds = wr.GetRequestStream(); var bytes = Encoding.ASCII.GetBytes(sparqlUpdate); ds.Write(bytes, 0, bytes.Length); var resp = wr.GetResponse() as HttpWebResponse; if (resp.StatusCode == HttpStatusCode.OK) { Logging.LogDebug("Update successful"); } else { Logging.LogDebug("Not a 200"); } resp.Close(); } catch(Exception ex) { Logging.LogError(1, "Unable to apply fragment for resourceUri {0} {1}", ex.Message, ex.StackTrace); } }
static IGraph CreateNuspecGraph(XDocument nuspec, string baseAddress, XslCompiledTransform xslt) { XsltArgumentList arguments = new XsltArgumentList(); arguments.AddParam("base", "", baseAddress); arguments.AddParam("extension", "", ".json"); arguments.AddExtensionObject("urn:helper", new XsltHelper()); XDocument rdfxml = new XDocument(); using (XmlWriter writer = rdfxml.CreateWriter()) { xslt.Transform(nuspec.CreateReader(), arguments, writer); } XmlDocument doc = new XmlDocument(); doc.Load(rdfxml.CreateReader()); IGraph graph = new Graph(); RdfXmlParser rdfXmlParser = new RdfXmlParser(); rdfXmlParser.Load(graph, doc); return graph; }
public static IGraph GraphFromXml(XDocument original, XslCompiledTransform transform, XsltArgumentList arguments) { XDocument rdfxml = new XDocument(); using (XmlWriter writer = rdfxml.CreateWriter()) { transform.Transform(original.CreateReader(), arguments, writer); } RdfXmlParser rdfXmlParser = new RdfXmlParser(); XmlDocument doc = new XmlDocument(); doc.Load(rdfxml.CreateReader()); //DEBUG //using (var xmlWriter = XmlWriter.Create(Console.Out)) //{ // doc.WriteTo(xmlWriter); //} IGraph graph = new Graph(); rdfXmlParser.Load(graph, doc); return graph; }
public void ParsingBaseUriAssignmentRdfXml() { Graph g = new Graph(); g.BaseUri = new Uri("http://example.org/RdfXml"); System.IO.StringWriter strWriter = new System.IO.StringWriter(); RdfXmlWriter writer = new RdfXmlWriter(); writer.Save(g, strWriter); Console.WriteLine("Original Base URI: " + ShowBaseUri(g.BaseUri)); Console.WriteLine("Output using RdfXmlWriter:"); Console.WriteLine(strWriter.ToString()); Console.WriteLine(); Graph h = new Graph(); RdfXmlParser parser = new RdfXmlParser(); parser.Load(h, new System.IO.StringReader(strWriter.ToString())); Console.WriteLine("Base URI after round-trip using RdfXmlWriter: " + ShowBaseUri(h.BaseUri)); Assert.IsNotNull(h.BaseUri, "Base URI should not be null"); strWriter = new System.IO.StringWriter(); FastRdfXmlWriter fastWriter = new FastRdfXmlWriter(); fastWriter.Save(g, strWriter); Console.WriteLine("Output using FastRdfXmlWriter:"); Console.WriteLine(strWriter.ToString()); Console.WriteLine(); Graph i = new Graph(); parser.Load(i, new System.IO.StringReader(strWriter.ToString())); Console.WriteLine("Base URI after round-trip to FastRdfXmlWriter: " + ShowBaseUri(h.BaseUri)); Assert.IsNotNull(i.BaseUri, "Base URI should not be null"); }
public static void Main(string[] args) { StreamWriter output = new StreamWriter("RdfXmlTestSuite.txt"); Console.SetOut(output); try { int testsPassed = 0; int testsFailed = 0; bool passed, passDesired; //RdfXmlParser parser = new RdfXmlParser(RdfXmlParserMode.Streaming); RdfXmlParser parser = new RdfXmlParser(RdfXmlParserMode.DOM); NTriplesWriter ntwriter = new NTriplesWriter(); parser.TraceParsing = true; Graph g = new Graph(); output.WriteLine("## RDF/XML Test Suite"); output.WriteLine(); String[] dirs = Directory.GetDirectories("xmlrdf_tests"); foreach (String dir in dirs) { if (dir.Contains(".svn")) { continue; } String[] files = Directory.GetFiles(dir); foreach (String file in files) { if (!Path.GetExtension(file).Equals(".rdf")) { continue; } passed = false; passDesired = true; output.WriteLine("## Testing " + file); output.WriteLine("# Test Started at " + DateTime.Now.ToString(TestSuite.TestSuiteTimeFormat)); if (Path.GetFileNameWithoutExtension(file).StartsWith("error")) { passDesired = false; output.WriteLine("# Desired Result = Parsing Failed"); } else { output.WriteLine("# Desired Result = Parses OK"); } try { Debug.WriteLine("Testing file " + file); g = new Graph(); g.BaseUri = new Uri(XMLTestSuiteBaseURI); parser.Load(g, file); passed = true; } catch (IOException ioEx) { reportError(output, "IO Exception", ioEx); } catch (RdfParseException parseEx) { reportError(output, "Parsing Exception", parseEx); } catch (RdfException rdfEx) { reportError(output, "RDF Exception", rdfEx); } catch (Exception ex) { reportError(output, "Other Exception", ex); } finally { if (passed && passDesired) { //Passed and we wanted to Pass testsPassed++; output.WriteLine("# Result = Test Passed"); //Try to write output ntwriter.Save(g, Path.ChangeExtension(file, "out")); } else if (!passed && passDesired) { //Failed when we should have Passed testsFailed++; output.WriteLine("# Result = Test Failed"); //Show output output.WriteLine("Generated the following Triples before failing:"); foreach (Triple t in g.Triples) { Console.WriteLine(t.ToString()); } } else if (passed && !passDesired) { //Passed when we should have Failed testsFailed++; output.WriteLine("# Result = Test Failed"); } else { //Failed and we wanted to Fail testsPassed++; output.WriteLine("# Result = Test Passed"); } output.WriteLine("# " + g.Triples.Count() + " Triples generated"); output.WriteLine("# Test Ended at " + DateTime.Now.ToString(TestSuite.TestSuiteTimeFormat)); } output.WriteLine(); } } output.WriteLine(testsPassed + " Tests Passed"); output.WriteLine(testsFailed + " Tests Failed"); } catch (IOException ioEx) { reportError(output, "IO Exception", ioEx); } catch (RdfParseException parseEx) { reportError(output, "Parsing Exception", parseEx); } catch (RdfException rdfEx) { reportError(output, "RDF Exception", rdfEx); } catch (Exception ex) { reportError(output, "Other Exception", ex); } output.Close(); }
public static Object LoadFromReader(Reader r, string baseUri, org.openrdf.rio.RDFFormat rdff) { Object obj; if (rdff == dotSesameFormats.RDFFormat.N3) { obj = new Graph(); if (baseUri != null) ((IGraph)obj).BaseUri = new Uri(baseUri); Notation3Parser parser = new Notation3Parser(); parser.Load((IGraph)obj, r.ToDotNetReadableStream()); } else if (rdff == dotSesameFormats.RDFFormat.NTRIPLES) { obj = new Graph(); if (baseUri != null) ((IGraph)obj).BaseUri = new Uri(baseUri); NTriplesParser parser = new NTriplesParser(); parser.Load((IGraph)obj, r.ToDotNetReadableStream()); } else if (rdff == dotSesameFormats.RDFFormat.RDFXML) { obj = new Graph(); if (baseUri != null) ((IGraph)obj).BaseUri = new Uri(baseUri); RdfXmlParser parser = new RdfXmlParser(); parser.Load((IGraph)obj, r.ToDotNetReadableStream()); } else if (rdff == dotSesameFormats.RDFFormat.TRIG) { obj = new TripleStore(); TriGParser trig = new TriGParser(); trig.Load((ITripleStore)obj, new StreamParams(r.ToDotNetReadableStream().BaseStream)); } else if (rdff == dotSesameFormats.RDFFormat.TRIX) { obj = new TripleStore(); TriXParser trix = new TriXParser(); trix.Load((ITripleStore)obj, new StreamParams(r.ToDotNetReadableStream().BaseStream)); } else if (rdff == dotSesameFormats.RDFFormat.TURTLE) { obj = new Graph(); if (baseUri != null) ((IGraph)obj).BaseUri = new Uri(baseUri); TurtleParser parser = new TurtleParser(); parser.Load((IGraph)obj, r.ToDotNetReadableStream()); } else { throw new RdfParserSelectionException("The given Input Format is not supported by dotNetRDF"); } return obj; }
private Graph GetXmlDocumentAsGraph() { var g = new Graph(); if (_xmlParser == null) { _xmlParser = new RdfXmlParser(RdfXmlParserMode.DOM); //This is not to store the URIs in a static list by dotNetRDF (uses up a lot of mem) Options.InternUris = false; } _xmlParser.Load(g, _output); //add namespaces from the XML doc to the graph foreach (var nsPrefix in _namespaces.Keys) { if (!g.NamespaceMap.HasNamespace(nsPrefix)) g.NamespaceMap.AddNamespace(nsPrefix, new Uri(_namespaces[nsPrefix])); } return g; }
static void Main(string[] args) { var tf = new edu.stanford.nlp.trees.LabeledScoredTreeFactory(new CustomStringLabelFactory()); var str = "(x2 / score :null_edge(x1 / null_tag) :null_edge(x3 / null_tag) :time(xap0 / before :quant(x5 / temporal - quantity :unit(y / year) :null_edge(x4 / null_tag))))"; var input = new java.io.StringReader(str); var treeReader = new edu.stanford.nlp.trees.PennTreeReader(input, tf, new CustomTreeNormalizer(), new CustomTokenizerAdapter(input)); var t = treeReader.readTree(); TreePrint p = new TreePrint("penn"); p.printTree(t); //READ RST INFORMATION RSTTree tree = new RSTTree("lincon"); tree.Load(Path.Combine(Root, "rst.xml")); tree.EvaluateODonell(); var sum = tree.Summarize(); //READ AMR INFORMATION FOR EACH EDU AND ASSOCIATTE THE ODONELL SCORE IGraph g = new Graph(); var parser = new VDS.RDF.Parsing.RdfXmlParser(); // NTriplesParser ntparser = new NTriplesParser(); parser.Load(g, Path.Combine(Root, "output.xml")); var document = new AMRDocument(); document.Load(g); foreach (var item in document.EDUSentences) { item.ApplyRSTWeight(sum.Where(c => c.edu == item.Id).Select(c => c.Weight).First()); } //var rstdocument = new RSTDocumentRepository(); //rstdocument.DeleteAllNodes(); //rstdocument.Save(tree); AMRNEORepository repo = new AMRNEORepository(); repo.DeleteAllNodes(); repo.SaveDocument(document); //var ids = Helper.ReadIds(g); //foreach (var item in ids) //{ // item.sentence = Helper.GetSentence(g, item); // item.AddNodes(g); // if (item.id == 22) // { // Console.WriteLine(item.urlid); // Console.WriteLine(item.sentence); // Console.WriteLine(item.Root.uriid); // Console.WriteLine(item.Root.Term.uriid); // Console.WriteLine(item.Root.Term.type); // } //} //SparqlQueryParser qparser = new SparqlQueryParser(); ////Then we can parse a SPARQL string into a query //StringBuilder querystr = new StringBuilder(); //querystr.AppendLine("PREFIX amr-core: <http://amr.isi.edu/rdf/core-amr#>"); //querystr.AppendLine("PREFIX amr-data: <http://amr.isi.edu/amr_data#>"); //querystr.AppendLine("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"); //querystr.AppendLine("PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>"); //querystr.AppendLine("PREFIX amr-terms: <http://amr.isi.edu/rdf/amr-terms#>"); ////querystr.AppendLine("SELECT ?p WHERE { ?s rdf:type ?p }"); ////querystr.Append("SELECT ?s ?sentence ?id ?root ?rtype ?amrtype"); //querystr.Append("SELECT ?root ?rtype ?amrtypelbl "); //querystr.Append("WHERE {"); //querystr.Append("?s amr-core:has-sentence ?sentence."); //querystr.Append("?s amr-core:has-id ?id."); //querystr.Append("?s amr-core:root ?root. "); //querystr.Append("?root rdf:type ?rtype. "); //querystr.Append("?rtype rdf:type ?amrtype. "); //querystr.Append("?amrtype rdfs:label ?amrtypelbl. "); //querystr.Append("}"); //SparqlQuery q = qparser.ParseFromString(querystr.ToString()); ////http://amr.isi.edu/rdf/core-amr#has-id //var rset = (SparqlResultSet)g.ExecuteQuery(q); //var SB = new StringBuilder(); //if (rset.Result && rset.Results.Count > 0) //{ // foreach (var result in rset.Results) // { // foreach (var r in result) // { // Console.WriteLine(r.Key + " " + r.Value); // } // //Do what you want with each result // } //} //File.WriteAllText("dic.txt", SB.ToString()); //http://amr.isi.edu/amr_data/22#root01 //foreach (var item in g.Triples) //{ // Console.WriteLine(item.Subject); //} //foreach (var node in g.Nodes) //{ // Console.WriteLine(node.ToString()); //} //g.SaveToFile("output.rdf"); }
static void Main(string[] args) { IGraph g = new Graph(); IGraph h = new Graph(); var parser = new VDS.RDF.Parsing.RdfXmlParser(); // NTriplesParser ntparser = new NTriplesParser(); //Load using a Filename parser.Load(g, Path.Combine(Root, "edus.amr.xml")); var ids = Helper.ReadIds(g); foreach (var item in ids) { item.sentence = Helper.GetSentence(g, item); item.AddRoot(g); Console.WriteLine(item.id); Console.WriteLine(item.urlid); Console.WriteLine(item.sentence); Console.WriteLine(item.Root.uriid); Console.WriteLine(item.Root.Term.uriid); Console.WriteLine(item.Root.Term.type); } //SparqlQueryParser qparser = new SparqlQueryParser(); ////Then we can parse a SPARQL string into a query //SparqlQuery q = // qparser.ParseFromString("SELECT ?s ?x ?p WHERE { ?s ?x ?p }"); ////http://amr.isi.edu/rdf/core-amr#has-id //var rset = (SparqlResultSet)g.ExecuteQuery(q); //var SB = new StringBuilder(); //if (rset.Result && rset.Results.Count > 0 ) //{ // foreach (var result in rset.Results) // { // foreach (var r in result) // { // SB.AppendLine(r.Key + " " + r.Value); // Console.WriteLine(r.Key + " " + r.Value); // } // //Do what you want with each result // } //} //File.WriteAllText("dic.txt", SB.ToString()); //http://amr.isi.edu/amr_data/22#root01 //foreach (var item in g.Triples) //{ // Console.WriteLine(item.Subject); //} //foreach (var node in g.Nodes) //{ // Console.WriteLine(node.ToString()); //} //g.SaveToFile("output.rdf"); }
/// <summary> /// Выполнение Sparql-запроса /// </summary> /// <param name="sparqlCommandText">Текст Sparql-запроса</param> /// <returns>Результат запроса в виде текста</returns> public string ExecuteQuery(string sparqlCommandText) { using (Graph baseGraph = new Graph()) { RdfXmlParser fileParser = new RdfXmlParser(); foreach (string fileName in FilesToQuery) { if (String.IsNullOrWhiteSpace(fileName)) continue; using (Graph g = new Graph()) { try { fileParser.Load(g, fileName); baseGraph.Merge(g); } catch (Exception ex) { throw new Exception(String.Format("Ошибка при обработке файла {0}\r\n{1}",fileName, ex.Message), ex); } } } var resultSet = baseGraph.ExecuteQuery(sparqlCommandText); if (resultSet is SparqlResultSet) { SparqlResultSet outputSet = resultSet as SparqlResultSet; if (outputSet.IsEmpty) QueryResult = "Пустой результат"; else { StringBuilder outputString = new StringBuilder(); foreach (SparqlResult result in outputSet.Results) outputString.AppendLine(result.ToString()); QueryResult = outputString.ToString(); } } else if (resultSet is Graph) { Graph resultGraph = resultSet as Graph; if (resultGraph.IsEmpty) QueryResult = "Пустой граф"; else QueryResult = VDS.RDF.Writing.StringWriter.Write(resultGraph, new RdfXmlWriter()); } else { QueryResult = string.Format("Неизвестный результат: {0}", resultSet.GetType()); } return QueryResult; } }
public void ParsingRdfXmlStreaming() { try { RdfXmlParser parser = new RdfXmlParser(RdfXmlParserMode.Streaming); parser.TraceParsing = true; Graph g = new Graph(); parser.Load(g, "example.rdf"); TestTools.ShowGraph(g); } catch (Exception ex) { TestTools.ReportError("Error", ex, true); } }
/// <summary> /// Internal Method which performs multi-threaded reading of data /// </summary> private void LoadGraphs(FolderStoreParserContext context) { //Create the relevant Parser IRdfReader parser; switch (context.Format) { case FolderStoreFormat.Turtle: parser = new TurtleParser(); break; case FolderStoreFormat.Notation3: parser = new Notation3Parser(); break; case FolderStoreFormat.RdfXml: parser = new RdfXmlParser(); break; default: parser = new TurtleParser(); break; } try { String file = context.GetNextFilename(); while (file != null) { //Read from Disk Graph g = new Graph(); String sourceFile = Path.Combine(context.Folder, file); parser.Load(g, sourceFile); //Add to Graph Collection foreach (Triple t in g.Triples) { if (context.Terminated) break; if (!context.Handler.HandleTriple(t)) ParserHelper.Stop(); } if (context.Terminated) break; //Get the Next Filename file = context.GetNextFilename(); } } catch (ThreadAbortException) { //We've been terminated, don't do anything #if !SILVERLIGHT Thread.ResetAbort(); #endif } catch (RdfParsingTerminatedException) { context.Terminated = true; context.ClearFilenames(); } catch (Exception ex) { throw new RdfStorageException("Error in Threaded Reader in Thread ID " + Thread.CurrentThread.ManagedThreadId, ex); } }
public void ParsingRdfXmlEmptyElement() { String fragment = @"<?xml version='1.0'?><rdf:RDF xmlns:rdf='" + NamespaceMapper.RDF + @"' xmlns='http://example.org/'><rdf:Description rdf:about='http://example.org/subject'><predicate rdf:resource='http://example.org/object' /></rdf:Description></rdf:RDF>"; Graph g = new Graph(); RdfXmlParser parser = new RdfXmlParser(RdfXmlParserMode.Streaming); parser.TraceParsing = true; VDS.RDF.Parsing.StringParser.Parse(g, fragment, parser); foreach (Triple t in g.Triples) { Console.WriteLine(t.ToString()); } }
public void TestRdfXmlExport() { CopyTestDataToImportFolder("simple.txt"); var storeName = "TestRdfXmlExport_" + DateTime.Now.Ticks; var client = GetClient(); client.CreateStore(storeName); var importJob = client.StartImport(storeName, "simple.txt"); importJob = WaitForJob(importJob, client, storeName); Assert.That(importJob.JobCompletedOk, "Import failed: {0} - {1}", importJob.StatusMessage, importJob.ExceptionInfo); var pathToExport = Path.Combine(Configuration.StoreLocation, "import", "simple.rdf"); if (File.Exists(pathToExport)) File.Delete(pathToExport); var exportJob = client.StartExport(storeName, "simple.rdf", exportFormat: RdfFormat.RdfXml, graphUri: Constants.DefaultGraphUri); exportJob = WaitForJob(exportJob, client, storeName); Assert.That(exportJob.JobCompletedOk, "Export failed: {0} - {1}", exportJob.StatusMessage, exportJob.ExceptionInfo); Assert.That(File.Exists(pathToExport)); var g = new Graph(); var parser = new RdfXmlParser(); parser.Load(g, pathToExport); // TODO: Validate expected content }
//static void Model_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) //{ // if (e.PropertyName == "ConsoleOutput") // Console.WriteLine((sender as ProcessViewModel).ConsoleOutput); //} /// <summary> /// https://bitbucket.org/dotnetrdf/dotnetrdf/wiki/User%20Guide /// </summary> static void TestRDF() { IGraph g = new Graph(); RdfXmlParser fileParser = new RdfXmlParser(); //fileParser.Load(g, "schema.xml"); fileParser.Load(g, "TestRdf.xml"); //SparqlQueryParser queryParser = new SparqlQueryParser(); //queryParser.ParseFromString("SELECT * WHERE { ?s a ?type }"); //VDS.RDF.Writing.StringWriter.Write(g, new RdfXmlWriter()) StringBuilder div = new StringBuilder(); XElement rdf = XElement.Parse(VDS.RDF.Writing.StringWriter.Write(g, new RdfXmlWriter())); foreach (XElement element in rdf.Elements()) { div.AppendFormat("<div itemscope itemtype=\"{0}/{1}\">", element.Name.NamespaceName.TrimEnd('/'), element.Name.LocalName); div.AppendLine(); foreach (XElement content in element.Elements()) { div.AppendFormat("<meta itemprop=\"{0}\" content=\"{1}\">", content.Name.LocalName, content.Value); div.AppendLine(); } div.AppendLine("</div>"); } var output = g.ExecuteQuery("SELECT * WHERE { ?s a ?type }"); SparqlParameterizedString query = new SparqlParameterizedString(); query.Namespaces.AddNamespace("rdf", new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#")); query.Namespaces.AddNamespace("owl", new Uri("http://www.w3.org/2002/07/owl#")); query.Namespaces.AddNamespace("xsd", new Uri("http://www.w3.org/2001/XMLSchema#")); query.Namespaces.AddNamespace("rdfs", new Uri("http://www.w3.org/2000/01/rdf-schema#")); query.Namespaces.AddNamespace("schema", new Uri("http://schema.org/")); query.Namespaces.AddNamespace("fact", new Uri("http://www.co-ode.org/ontologies/ont.owl#")); query.CommandText = "SELECT * WHERE { ?organization rdf:type fact:UniqueCompany }"; var output2 = g.ExecuteQuery(query); // var output2 = g.ExecuteQuery(@"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> // PREFIX owl: <http://www.w3.org/2002/07/owl#> // PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> // PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> // PREFIX schema: <http://schema.org/> // PREFIX fact:<http://www.co-ode.org/ontologies/ont.owl#> // SELECT * // WHERE { ?organization rdf:type fact:UniqueCompany }"); }